#!/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

from __future__ import print_function

import os
import sys
import syslog
import subprocess
import traceback

import isi.net.flexnet as flexnet

def main():
    # Get the stored subnet from the old config we migrated from
    try:
        output = subprocess.check_output(['/usr/bin/grep',
                'remote_support_subnet', sys.argv[1]]).strip()
    except subprocess.CalledProcessError as err:
        # NOTE: grep returns 2 for file errors and 1 for match and other errors.
        if err.returncode != 1:
            raise

        print('No subnet configuration found in %s, skipping conversion'
                % sys.argv[1], file=sys.stderr)
        return

    if not output:
        # Exit out if we can't find a value
        return

    subnet_option = output.split(' = ')[-1]
    subnet_option = subnet_option.strip('"')

    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
    subnet = flexcfg.find_subnet_by_name(subnet_option)
    assert subnet is not None, "Cannot find subnet '%s'" % subnet_option

    # Run the command to set that option
    subprocess.check_call(['/usr/bin/isi', 'remotesupport', 'connectemc',
            'modify', '--enabled=true', '--gateway_access_pools=%s:%s' %
            (subnet.name, subnet.pools[0].name)])

if __name__ == '__main__':
    try:
        main()
    except Exception as e:
        syslog.syslog(syslog.LOG_ERR, "Failed applying %s: %s" % (sys.argv[1],
                traceback.format_exc(),))
        sys.exit(os.EX_CONFIG)
