#!/usr/bin/env python

import os
import os.path
import re
import sys
import syslog
import traceback
import subprocess


import isi.app.lib.cluster as cluster
import isi.gconfig as gconfig
import isi.net.flexnet as flexnet
from isi.celog.constants import ESRS_PROVISIONED_FLAG
import isi.config.tardis as tardis
import isi.config.gcfg_vonefs as gcfg_vonefs

ESRS_IP_NAMESPACE = "esrs.ip.set"

def parse(subnet_pool_list):
    pairs = []
    for pair in subnet_pool_list:
        l = [str(x) for x in filter(None, re.split('[:.]', pair))]
        pairs.append({'subnet': l[0], 'pools': l[1].split(';')})

    return pairs

def main():
    tree = gconfig.Tree("remote-support")
    base = c = gconfig.open(tree)
    ctx = c.ctx_new()
    connectemc_cfg = ctx.read("connectemc")
    if not connectemc_cfg["enabled"]:
        if os.path.exists(ESRS_PROVISIONED_FLAG):
            os.remove(ESRS_PROVISIONED_FLAG)
        sys.exit(0)

    serialno = ""
    model = "ISILON-GW"
    my_devid = cluster.Cluster().local_devid()
    vonefs_config = gcfg_vonefs.get_vonefs_config_settings()

    if vonefs_config.software_unique_id != '':
        model = "ISILONSD"
        lnn = cluster.Cluster().devid_to_lnn(my_devid)
        serialno = vonefs_config.software_unique_id + '-' + str(lnn)
    else:
        serialno = cluster.DeviceInfo().serial_number()

    if not serialno:
        syslog.syslog(syslog.LOG_ERR, "Failed isi_run_gwext: need serial "
                "number")
        sys.exit(1)

    flexcfg = flexnet.config_try_load()
    subnet_pools_dict = parse(connectemc_cfg['gateway_access_pools'])

    ns = tardis.Namespace(ESRS_IP_NAMESPACE, tardis.TNS_O_CREAT)

    # Find all external IP's that from the allowed subnets
    # that match a node's devid
    addrs = []
    for subnet in flexcfg.subnets:
        for d in subnet_pools_dict:
            if subnet.name == d['subnet']:
                for pool in subnet.pools:
                    if pool.name in d['pools']:
                        for iid in pool.iface_ids:
                            if iid.devid == my_devid:
                                addrs += pool.get_addrs(iid)

    # If we can't find an IP then don't provision this node
    if not addrs:
        if os.path.exists(ESRS_PROVISIONED_FLAG):
            os.remove(ESRS_PROVISIONED_FLAG)
        sys.exit(0)

    # Save the IP in tardis so we know which IP ESRS
    # is using to connect to this node
    found = False
    kvs = tardis.KVSet()
    for my_address in addrs:
        my_address = str(my_address)
        try:
            kvs[str(my_devid)] = my_address
            ns.create(kvs)
            found = True
            break
        except Exception as e:
            print "create failed: %s\n" % str(e)

        while True:
            ns.sync(kvs)
            kvs[str(my_devid)] = my_address
            try:
                ns.update(kvs)
                found = True
                break
            except Exception as e:
                print "update failed: %s" % str(e)

    # If we can't find an IP from the list that isn't in use
    # then don't provision the node
    if not found:
        if os.path.exists(ESRS_PROVISIONED_FLAG):
            os.remove(ESRS_PROVISIONED_FLAG)
        sys.exit(0)

    # Call GWExt to send out node IP, serial no., and gateway IP
    # to ESRS
    primary_gateway = connectemc_cfg["primary_esrs_gateway"]
    secondary_gateway = connectemc_cfg["secondary_esrs_gateway"]

    os.chdir("/opt/connectemc/ESRSGWExt")
    for gateway in (primary_gateway, secondary_gateway):
        if gateway:
            ret = subprocess.call(["/usr/local/connectemc/ESRSGWExt/GWExt",
                                   "--devicesn=%s" % serialno,
                                   "--deviceip=%s" % my_address,
                                   "--gatewayip=%s" % gateway,
                                   "--model=%s" % model,
                                   "--operation=Manage"])
            ret = subprocess.call(["/usr/local/connectemc/ESRSGWExt/GWExt",
                                   "--devicesn=%s" % serialno,
                                   "--deviceip=%s" % my_address,
                                   "--gatewayip=%s" % gateway,
                                   "--model=%s" % model,
                                   "--operation=Update"])
            open(ESRS_PROVISIONED_FLAG, "w").close()

if __name__ == '__main__':
    try:
        main()
    except Exception as e:
        syslog.syslog(syslog.LOG_ERR,
                "Failed isi_run_gwext %s" % (traceback.format_exc(),))
        sys.exit(1)
