#!/usr/bin/python3
# calld, monitor ofono for incoming voice calls
# from ofono test script monitor-ofono I see
# {VoiceCallManager} [CallAdded] /gobi_0/voicecall01 { State = dialing, LineIdentification = 18165179265, Name = , Multiparty = False, RemoteHeld = False, RemoteMultiparty = False, Emergency = False }
# {VoiceCall} [/gobi_0/voicecall01] State = incoming
# {VoiceCall} [/gobi_0/voicecall01] State = disconnected
# {VoiceCallManager} [/gobi_0/voicecall01] CallRemoved

from gi.repository import GLib

import dbus
import dbus.mainloop.glib
import sys
import datetime
import os

incoming_number=None

with open('/var/spool/calls', 'a') as spool:
	spool.write('# calld started at %s\n' % datetime.datetime.now())

def call_added(name, value, interface):
	# save the phone number for later since an incoming call
	# really comes as two events: CallAdded and VoiceCall state = incoming
	global incoming_number
	incoming_number = value['LineIdentification']

def incoming_call(name, value, path, interface):
	iface = interface[interface.rfind(".") + 1:]
	if iface == "VoiceCall" and name == "State" and value == "incoming":
		os.system("ring call %s" % (incoming_number))
		with open('/var/spool/calls', 'a') as spool:
			spool.write("%s incoming %s\n" % (datetime.datetime.now(), incoming_number))

def removed_call(name):
	os.system("ring hangup %s" % (incoming_number))
	with open('/var/spool/calls', 'a') as spool:
		spool.write("%s hungup %s\n" % (datetime.datetime.now(), incoming_number))

if __name__ == '__main__':
	dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

	bus = dbus.SystemBus()

	bus.add_signal_receiver(incoming_call,
				bus_name="org.ofono",
				signal_name = "PropertyChanged",
				path_keyword="path",
				interface_keyword="interface")

	bus.add_signal_receiver(call_added,
				bus_name="org.ofono",
				signal_name="CallAdded",
				interface_keyword="interface")

	bus.add_signal_receiver(removed_call,
				bus_name="org.ofono",
				signal_name="CallRemoved")

	mainloop = GLib.MainLoop()
	mainloop.run()
# TODO on keyboard interrupt or exception, write a comment about smsd crashing/ending to the spool
