#!/usr/bin/python3

import os
import socket
import dbus
import subprocess
from urllib.parse import urlparse
from syslog import syslog

connection = os.getenv('CONNECTION_ID')
modem_path = os.getenv('DEVICE_IFACE')
net_device = os.getenv('DEVICE_IP_IFACE')

if modem_path is None or connection is None:
	os._exit(0)

if not modem_path.startswith('/') or not connection.startswith('/'):
	os._exit(0)

syslog("Adding route for MMS connection {} on {} ({})".format(connection, modem_path, net_device))

try:
	context_id = connection.split('/')[2]

	bus = dbus.SystemBus()

	context_path = "{}/{}".format(modem_path, context_id)

	ofono_ril = dbus.Interface(bus.get_object('org.ofono', context_path),
	                           "org.ofono.ConnectionContext")

	properties = ofono_ril.GetProperties()

	mobile_settings = properties["Settings"]
	mobile_gw = mobile_settings["Gateway"]

	if "MessageProxy" in properties:
		mmsproxy = properties["MessageProxy"]
		routed_ip = socket.gethostbyname(mmsproxy.partition(':')[0])
	elif "MessageCenter" in properties:
		mmscenter = properties["MessageCenter"]
		routed_ip = socket.gethostbyname(urlparse(mmscenter).netloc)
	else:
		raise EnvironmentError("MessageProxy or MessageCenter for {} missing".format(context_path))

	syslog("{}: adding route for {} ({}) via {} ({})".format(modem_path, mmsproxy, routed_ip, mobile_gw, net_device))
	subprocess.call(["ip", "route", "add", routed_ip, "dev", net_device, "proto", "static"])
except Exception as e:
	syslog("failed to add route: {}".format(e))
	os._exit(0)

