#!/usr/bin/env python
# This script will take the subnet configured from the previous remote_support_subnet
# option on Pre-Riptide clusters and take the first pool from that subnet and
# set the new gateway_access_pools option

import sys
import syslog
import commands
import traceback

import isi.gconfig as gconfig
import isi.net.flexnet as flexnet

def main():
    # Grab the remote-support gconfig tree
    tree = gconfig.Tree("remote-support")
    c = gconfig.open(tree)
    ctx = c.ctx_new()
    connectemc_cfg = ctx.read("connectemc")

    if connectemc_cfg["enabled"]:
        # Get the stored subnet from the old config we migrated from
        cat = "cat /ifs/.ifsvar/remote_support.gc.migrated | grep remote_support_subnet"
        output = commands.getoutput(cat)
        if output == '':
            # Exit out if we can't find a value
            return
        subnet_option = output.split(' = ')[-1]
        subnet_option = subnet_option.strip('"')
        print subnet_option

        flexcfg = flexnet.config_try_load()

        # Use the subnet to find the first pool in that subnet
        # NOTE We have discussed this with Product Management
        # and they wanted this solution which might send data back
        # opposed to disabling ESRS which will guarantee we won't
        for subnet in flexcfg.subnets:
            if subnet.name == subnet_option:
                print subnet.name
                for pool in subnet.pools:
                    print pool.name
                    pool_option = pool.name
                    break

        # Run the command to set that option
        cmd = 'isi remotesupport connectemc modify --enabled=true --gateway_access_pools="%s:%s"' % \
                (subnet_option, pool_option)
        print cmd
        commands.getoutput(cmd)
    return

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