#!/usr/bin/python3
# encoding=utf-8
import sys
import subprocess
import re
import os

# if ip, openvpn or killall lie outside one of these paths, make sure to
# add it here
os.environ["PATH"] += ":/usr/bin:/usr/sbin:/bin:/sbin"

# the interface to watch out for going up/down.
MATCH_INTERFACE = "p4p1"

# regular expression to match the output of
#   ip addr show dev IFACE
# against (with IFACE being the interface NM just brought up). You can
# use this to restrict the start of openvpn to certain networks. Set to
# None to disable this check.
MATCH_ADDR = re.compile(r"^\s+inet\s+10\.13\.37\.1", re.M)

# working directory for openvpn
OPENVPN_DIR = "/etc/openvpn"

# path to the openvpn config file (relative to OPENVPN_DIR)
OPENVPN_CONFIG = "feynman.conf"

# NetworkManager gives us the interface going up/down as first argument,
# and the status as second argument
interface = sys.argv[1]
if interface != MATCH_INTERFACE:
    sys.exit(0)

status = sys.argv[2]
if status == "up":
    if MATCH_ADDR:
        output = subprocess.check_output(
            ["ip", "addr", "show", "dev", interface]
        ).decode("ascii")  # ip should never output something non-ascii
        if not MATCH_ADDR.match(output):
            # doesn't concern our interface
            sys.exit(0)
    # start openvpn
    subprocess.check_call(["openvpn", "--config", OPENVPN_CONFIG],
                          cwd=OPENVPN_DIR)
elif status == "down":
    # kill openvpn on shutdown
    subprocess.check_call(["killall", "openvpn"])
