#!/usr/bin/env python
"""toggle a dynamic service firewall on/off

Usage: %s DEVICE "up|down|status|list"
where DEVICE is a network interface, such as wlan0
This script starts or stops a firewall as defined in servicewall.py
"""

#from statefulfirewall import StateFulFireWall
from servicewall import servicewall
from servicewall import network_helpers
from sys import argv
from os import environ



def get_local_subnet(device):
    """Returns the local subnet iface is connected to."""
    try:
        essid = environ["CONNECTION_ID"]
        #uuid = environ["CONNECTION_UUID"]
    except KeyError:
        essid = ""
    return(essid, network_helpers.get_subnetwork(device))


if __name__ == "__main__":

    if len(argv) != 3:
        print(__doc__)
        raise SystemError("wrong number of arguments : %s" % " ".join(argv))
    device = argv[1]
    action = argv[2]
    #firewall = StateFulFireWall()
    firewall = servicewall.ServiceWall()

    if action == "up":
        if firewall.up:
            raise SystemExit()
        #essid, local_subnet = get_local_subnet(device)
        firewall.start()

    elif action == "down":
        if not firewall.up:
            raise SystemExit()
        firewall.stop()

    elif action == "connectivity-change":
        if firewall.up:
            #essid, local_subnet = get_local_subnet(device)
            local_subnet = network_helpers.get_subnetwork()
            if local_subnet != firewall.subnetwork:
                firewall.down()
                firewall.up()

    elif action == "status":
        if firewall.up:
            print("up")
        else:
            print("down")

    else:
        print(__doc__)
        raise SystemError("wrong usage : %s" % " ".join(argv))

