#!/usr/bin/env python

import traceback
import syslog
import os
import re
import sys
from optparse import OptionParser

import isi.celog.upgrade_utils as utils
import isi.celog.celog_config_api as config

CELOG_IFSVAR_DIR = "/ifs/.ifsvar/modules/celog/"

NOTIFICATION_UPGRADE_FILE = CELOG_IFSVAR_DIR + "notification_upgrade.lock"

NOTIFICATION_UPGRADE_DONE_FILE = CELOG_IFSVAR_DIR + "notification_upgrade_done"

if __name__ == "__main__":

    try:
        parser = OptionParser()
        opts, args = parser.parse_args()

        if args:
            xmlfile = args[0]
        else:
            xmlfile = utils.DEFAULT_SOURCE

        # Lock a file so nodes don't stomp on each other.
        lockfd = os.open(NOTIFICATION_UPGRADE_FILE, 
                os.O_RDONLY | os.O_CREAT | os.O_EXLOCK, 0600)
        os.chmod(NOTIFICATION_UPGRADE_FILE, 0600)
                
        if os.path.exists(NOTIFICATION_UPGRADE_DONE_FILE):
            sys.exit(0)
            
        if os.path.exists(xmlfile):

            parser = utils.NotificationConfigParser()
            parser.parse_file(xmlfile)

            configAPI = config.CelogConfigAPI()
            for n, s in parser.cfgs.iteritems():
                
                # For this one-time upgrade, if a rule exists for Isilon
                # Support, create the new style SupportIQ rules
                if re.match("Isilon Support", n):
                    configAPI.enable_isilonsupport_notifications()
                    configAPI.enable_supportiq_notifications()
                else:
                    configAPI.add_notification_setting(utils.build_cfg(n, s))

            curr_contact_cfg = configAPI.get_contact_settings()
            curr_contact_cfg.update(parser.contact_info)
            configAPI.set_contact_settings(curr_contact_cfg)

            if parser.mail_relay or parser.mail_sender or parser.mail_subject:

                curr_celog_cfg = configAPI.get_celog_settings()
                if parser.mail_relay:
                    curr_celog_cfg['mail_relay'] = parser.mail_relay
                if parser.mail_sender:
                    curr_celog_cfg['mail_sender'] = parser.mail_sender
                if parser.mail_subject:
                    curr_celog_cfg['mail_subject'] = parser.mail_subject

                configAPI.set_celog_settings(curr_celog_cfg)
        fd = os.open(NOTIFICATION_UPGRADE_DONE_FILE, \
                        os.O_CREAT | os.O_RDONLY, 0400)
        os.close(fd)
        os.chmod(NOTIFICATION_UPGRADE_DONE_FILE, 0400)
        os.close(lockfd)
        syslog.syslog(syslog.LOG_NOTICE, "Completed notification config "
                "upgrade.")
    except Exception:
        syslog.syslog(syslog.LOG_ERR, "Error notification config "
                "upgrade failed.")
        syslog.syslog(syslog.LOG_ERR, traceback.format_exc())

