#!/usr/bin/python

import logging
import os
import sys
import syslog

import isi.config.xml as xml
import isi.config as iconf
import isi.net.flexnet as flexnet

IFS_BACKUP_PATH = "/ifs/.ifsvar/tmp"
LOG_FILE = os.path.join(IFS_BACKUP_PATH, "cbind-service-upgrade.log")
CBIND_SERVICE_OVERRIDE_FILE = '/etc/mcp/override/isi_cbind_d'

LOGGER = logging.getLogger("cbind_service_upgrade")

def cbind_service_upgrade():
    """
    Remove the mcp override service file.
    """
    LOGGER.info("Running cbind upgrade script")
    if (os.path.exists(CBIND_SERVICE_OVERRIDE_FILE)):
        config = xml.XMLConfig(CBIND_SERVICE_OVERRIDE_FILE)
        # if the service is disabled, make certain it is disabled
        # in the flxnet config
        for child in config.getChildren():
            if child.getAttribute('attribute') == 'enable' and  child.getAttribute('value') == 0:
                flx_config = flx.config_open()
                if (flx_config.dns_cache_enabled):
                    flx_config.dns_cache_enabled = False
                    flx_config.save()
                flx.close()
        os.unlink(CBIND_SERVICE_OVERRIDE_FILE)
        os.system("pkill -F /var/run/isi_mcp_master.pid")
    
def main():
    try:
        lnn = "Node %d -" % iconf.getNode()['node id']
        lfmt = lnn + "%(asctime)s - %(levelname)s - %(message)s"
        LOGGER.setLevel(logging.INFO)
        fhandler = logging.FileHandler(LOG_FILE, 'a')
        fhandler.setLevel(logging.INFO)
        fhandler.setFormatter(logging.Formatter(lfmt))
        LOGGER.addHandler(fhandler)
    except EnvironmentError as err:
        syslog.syslog(syslog.LOG_NOTICE,
                      "Error running cbind service upgrade script: %s" % err)
        return 1

    try:
        os.chmod(LOG_FILE, 0640)
    except OSError as err:
        # log chmod errors and continue
        syslog.syslog(syslog.LOG_NOTICE,
                      "Error chmod'ing %s (errno: %d)" % (LOG_FILE, err.errno))

    cbind_service_upgrade()
    return 0


if __name__ == "__main__":
    sys.exit(main())