#!/usr/bin/python
import ConfigParser
import argparse
import io
import glob
import os
import pwd
import urllib
import uuid
import re

RAND_STRING = "__RANDOM__"
CONFIG_ROOT = "/var/efw"
PRODUCT_SETTINGS = "/usr/lib/efw/product/default/settings"

INTERFACE_UP = False

def parsecmdline():
    f = open("/proc/cmdline").read().strip()
    l = [x for x in f.split(" ")]
    d = map(lambda x: x.split("="), l)
    key, nokey = {}, []
    for k in d:
        if len(k) == 1:
            nokey.append(k[0])
        elif len(k) == 2:
            key[k[0]] = k[1]
    return key, nokey

def run(cmd):
    return os.system(cmd)

def writeSettings(params, settings_file, mode="w"):
    content = '\n'.join(['='.join(x) for x in params.items()])
    with open(settings_file, mode) as f:
        f.write(content)
    nobody = pwd.getpwnam("nobody")
    os.chown(settings_file, nobody.pw_uid, nobody.pw_gid)

def conf_argument(conf, section, key, default=None):
    try:
        return conf.get(section, key)
    except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
        return default

def download_file(url, path):
    urllib.urlretrieve(url, path)

def get_dhcp(interface):
    k = run("dhclient %s" % interface)
    if k != 0:
        raise RuntimeError("Can't get IP address from dhcp")
    return 0

def teardown_dhcp():
    return run("killall -9 dhclient")

def setup_interface(interface):
    global INTERFACE_UP
    if INTERFACE_UP:
        return
    run("ip link set dev %s up" % interface)
    get_dhcp(interface)
    INTERFACE_UP = True

def teardown_interface(interface):
    global INTERFACE_UP
    if not INTERFACE_UP:
        return
    teardown_dhcp()
    run("ip addr flush dev %s" % interface)
    run("ip link set dev %s down" % interface)
    INTERFACE_UP = False

def get_hostname_prefix(fromfile=PRODUCT_SETTINGS, default="ofw"):
    try:
        r = re.compile('HOSTNAMEPREFIX=(.*)')
        for l in open(fromfile).readlines():
            if r.match(l):
                return r.match(l).group(1)
    except Exception:
        pass
    return default

def setup_hostname(hostname, domainname):
    host_settings_file = os.path.join(CONFIG_ROOT, "host", "settings")
    if os.path.exists(host_settings_file) and hostname == RAND_STRING:
        return
    if hostname == RAND_STRING:
        prefix = get_hostname_prefix(default="ofw")
        hostname = prefix + "-" + str(uuid.uuid4()).replace("-", "")[:10]
    params = {}
    params["HOSTNAME"] = hostname
    params["DOMAINNAME"] = domainname
    writeSettings(params, host_settings_file)

def install_signatures(interface=None, signatures_url=None):
    tar_files = glob.glob("/usr/share/signatures/signatures*.tar.gz")
    if tar_files:
        run("tar --no-same-owner -zxf /usr/share/signatures/signatures*.tar.gz -C /")
        for x in tar_files:
            os.remove(x)
        os.rmdir("/usr/share/signatures")
    elif interface == None or signatures_url == None:
        return
    else:
        setup_interface(interface)
        tar_file = os.path.join("/var", "tmp", os.path.basename(signatures_url))
        download_file(signatures_url, tar_file)
        run("tar --no-same-owner -zxf %s -C /" % tar_file)
        os.remove(tar_file)

def install_provisioning_certificate(interface=None, cert_url=None):
    try:
        cert_file = glob.glob("/root/*-cert.pem")[0]
    except IndexError:
        cert_file = ''
    if not cert_file:
        if interface == None or cert_url == None:
            return
        setup_interface(interface)
        cert_file = os.path.join("/", "root", os.path.basename(cert_url))
        download_file(cert_url, cert_file)
    if not os.path.exists(cert_file):
        return
    cert_dir = os.path.join("/", "usr", "lib", "efw", "provisioning")
    cert_dest_file = os.path.join(cert_dir, "cert.pem")
    run("mkdir -p %s" % cert_dir)
    run("cp %s %s" % (cert_file, cert_dest_file))
    os.remove(cert_file)

def ntp_sync(interface=None, ntp_server=None):
    if interface == None or ntp_server == None:
        return
    setup_interface(interface)
    if run("ntpdate %s" % ntp_server) == 0:
        run("hwclock --utc --systohc")

def set_root_pwd(root_password):
    run("echo %s | chrootpasswd" % root_password)

def set_admin_pwd(admin_password):
    f = os.path.join(CONFIG_ROOT, "auth", "users")
    run("/usr/bin/htpasswd -c -m -b %s admin '%s'" % (f, admin_password))


def calc_cidr(addr, netmask):
    bb = ""
    for b in netmask.split("."):
        bb += bin(int(b))[2:]
    prefix = bb.count("1")
    return "%s/%d" % (addr, prefix)

def setup_green(address, netmask, netaddress, broadcast):
    eth_settings_file = os.path.join(CONFIG_ROOT, "ethernet", "settings")
    params = {}
    params["GREEN_ADDRESS"] = address
    params["GREEN_NETMASK"] = netmask
    params["GREEN_NETADDRESS"] = netaddress
    params["GREEN_BROADCAST"] = broadcast
    params["GREEN_IPS"] = calc_cidr(address, netmask)
    params["CONFIG_TYPE"] = "0"
    params["GREEN_DEV"] = "br0"
    writeSettings(params, eth_settings_file)

def setup_main(keymap, language):
    main_settings_file = os.path.join(CONFIG_ROOT, "main", "settings")
    params = {}
    if keymap is not None:
        params["KEYMAP"] = keymap
    if language is not None:
        params["LANGUAGE"] = language
    if not params:
        return
    writeSettings(params, main_settings_file)

def setup_timezone(tz):
    tz_dst_file = "/etc/localtime"
    tz_src_file = os.path.join("/usr/share/zoneinfo/posix", tz)
    if not os.path.exists(tz_src_file):
        return
    if os.path.exists(tz_dst_file):
        os.unlink(tz_dst_file)
    os.symlink(tz_src_file, tz_dst_file)

    time_settings_file = os.path.join(CONFIG_ROOT, "time", "settings")
    params = {'TIMEZONE': tz}
    writeSettings(params, time_settings_file)

def setup_activation(activation_code):
    activation_file = os.path.join(CONFIG_ROOT, "en", "activation")
    open(activation_file, "w").write("%s\n" % activation_code)

# TODO
# Serial deactivating on inittab and grub?

def do_without_unattended():
    setup_hostname(RAND_STRING, "localdomain")
    install_signatures()

def do_with_unattended(conf, interface):
    hostname = conf_argument(conf, "hostname", "hostname", RAND_STRING)
    domainname = conf_argument(conf, "hostname", "domainname", "localdomain")
    setup_hostname(hostname, domainname)

    root_pwd = conf_argument(conf, "password", "root")
    if root_pwd is not None:
        set_root_pwd(root_pwd)

    admin_pwd = conf_argument(conf, "password", "admin")
    if admin_pwd is not None:
        set_admin_pwd(admin_pwd)

    ntp_sync(interface, conf_argument(conf, "ntp", "server"))

    signature_url = conf_argument(conf, "signatures", "url")
    install_signatures(interface, signature_url)

    cert_url = conf_argument(conf, "provisioning", "cert_url")
    install_provisioning_certificate(interface, cert_url)

    green_address = conf_argument(conf, "green", "address")
    green_netmask = conf_argument(conf, "green", "netmask")
    green_netaddress = conf_argument(conf, "green", "netaddress")
    green_broadcast = conf_argument(conf, "green", "broadcast")
    if green_address is not None:
        setup_green(green_address, green_netmask, green_netaddress, green_broadcast)

    tz = conf_argument(conf, "intl", "timezone")
    if tz is not None:
        setup_timezone(tz)

    keymap = conf_argument(conf, "intl", "keymap")
    language = conf_argument(conf, "intl", "language")
    setup_main(keymap, language)

    activation_code = conf_argument(conf, "activation", "activation_key")
    if activation_code:
        setup_activation(activation_code.upper())

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-p", "--unattended-path", required=True)
    args = parser.parse_args()
    unattended_path = args.unattended_path
    interface = None
    installserver_ip = None
    if not os.path.exists(unattended_path):
        key, nokey = parsecmdline()
        try:
            interface = key['download_interface']
            installserver_ip = key['installserver_ip']
            unattended_url = "http://%s/%s" % (installserver_ip, key['unattended_url'].lstrip("/"))
        except KeyError:
            do_without_unattended()
            return
        setup_interface(interface)
        try:
            download_file(unattended_url, unattended_path)
        except Exception as e:
            print(e)
            teardown_interface(interface)
            return
    with open(unattended_path, "r") as f:
        unattended_conf = f.read()
    if installserver_ip is not None:
        unattended_conf = unattended_conf.replace("%%INSTALLSERVER%%", installserver_ip)
    conf = ConfigParser.ConfigParser()
    conf.readfp(io.BytesIO(unattended_conf))
    if interface is None:
        interface = conf_argument(conf, "main", "download_interface")
    try:
        do_with_unattended(conf, interface)
    except Exception as e:
        print(e)
    teardown_interface(interface)

if __name__ == "__main__":
    main()
