#!/usr/bin/python

from isi.celog.celog_config_api import CelogConfigAPI
from isi.celog_lib.config import Config
import isi.papi.basepapi as papi
import isi.sys.version as sysver
import json
import os
import time

PAPI_RETRIES = 30

REPORT_DIR = '/ifs/data/Isilon_Upgrade_Reports'
REPORT_FILE = '%s/notification_configuration.txt' % REPORT_DIR

OLD_CELOG_DB = '/ifs/.ifsvar/db/celog/events.db'
ARCHIVE_DB = '/ifs/.ifsvar/db/celog/events.db.pre8'

def recipients_match(channel_type, recipients, settings):
    if 'smtp' == channel_type:
        addresses = recipients.split(',')
        chan_addrs = settings['parameters'].get('address', [])
        if len(addresses) != len(chan_addrs):
            return False
        for addr in addresses:
            if addr not in chan_addrs:
                return False
        return True
    return False

class NotifcationRulesCopier(object):
    snmp = 0
    smtp = 0
    alert = 0

    def create_channel(self, channel_type, recipients):
        channel = {
            'type': channel_type
        }
        parameters = {}
        if 'snmp' == channel_type:
            self.snmp += 1
            ctr = self.snmp
            (community, host) = recipients.split('@')
            parameters['community'] = community
            parameters['host'] = host
        elif 'smtp' == channel_type:
            self.smtp += 1
            ctr = self.smtp
            parameters['address'] = recipients.split(',')
        else:
            assert(False)
        channel['name'] = "%s%d" % (channel_type, ctr)
        channel['parameters'] = parameters

        papi.post('3/event/channels', channel)
        self.load_channels()

    def load_notification_settings(self):
        api = CelogConfigAPI()
        objs = api.get_notification_settings()
        settings = {}
        for (key, setting) in objs.iteritems():
            settings[key] = api._setting_to_dict(setting)
        self.notifications = settings

    def load_channels(self):
        tries = 0
        while tries < PAPI_RETRIES:
            try:
                resp = papi.get('3/event/channels')
                break
            except RuntimeError:
                tries += 1
                if tries == PAPI_RETRIES:
                    raise
                time.sleep(1)
            except:
                raise
        channels = resp.body['channels']
        self.email_channels = []
        self.snmp_channels = {}
        for channel in channels:
            if 'smtp' == channel['type']:
                self.email_channels.append(channel)
            if 'snmp' == channel['type']:
                community = channel['parameters'].get('community', 'public')
                host = channel['parameters'].get('host', '')
                key = "%s@%s" % (community, host)
                self.snmp_channels[key] = channel

    def load_alerts(self):
        resp = papi.get('3/event/alert-conditions')
        self.alerts = resp.body['alert-conditions']

    def load_events(self):
        with open('/etc/celog/events.json') as ev_file:
            self.events = json.load(ev_file)
        self.categories = {}
        for event in self.events.keys():
            category = self.events[event]['category']
            if category not in self.categories:
                self.categories[category] = []
            self.categories[category].append(event)

    def load_eventgroups(self):
        with open('/etc/celog/eventgroups.json') as grp_file:
            self.groups = json.load(grp_file)
        for group in self.groups.keys():
            for event in self.groups[group]['symptoms']:
                if not 'eventgroups' in self.events[event]:
                    self.events[event]['eventgroups'] = []
                self.events[event]['eventgroups'].append(group)
        for event in self.events.keys():
            if not 'eventgroups' in self.events[event]:
                self.events[event]['eventgroups'] = [ event ]

    def find_channels(self, channel_type, recipients):
        if 'smtp' == channel_type:
            for channel in self.email_channels:
                if recipients_match(channel_type, recipients, channel):
                    return [ channel['id'] ]
            self.create_channel(channel_type, recipients)
            for channel in self.email_channels:
                if recipients_match(channel_type, recipients, channel):
                    return [ channel['id'] ]
        if 'snmp' == channel_type:
            for recipient in recipients.split(','):
                if recipient not in self.snmp_channels.keys():
                    self.create_channel(channel_type, recipient)
            channels = []
            for recipient in recipients.split(','):
                channels.append(self.snmp_channels[recipient]['id'])
            return channels
        return None

    def categorise(self, settings):
        categories = []
        categorised = {}
        uncategorised = []
        for spec in settings.values():
            event = unicode(spec['eventid'])
            if event in self.categories:
                categories.append(event)
            if event in self.events:
                category = self.events[event]['category']
                if category not in categorised:
                    categorised[category] = []
                categorised[category].append(spec)
        togo = []
        for category in categorised.keys():
            if category not in categories:
                uncategorised.extend(categorised[category])
                togo.append(category)
        for category in togo:
            categorised.pop(category, None)
        return (categorised, uncategorised)

    def notify_on(self, settings):
        categories = []
        wanted_categories = []
        eventgroups = set()
        categorised = {}
        for spec in settings.values():
            event = unicode(spec['eventid'])
            if event in self.categories:
                categories.append(event)
            if event in self.events:
                category = self.events[event]['category']
                if category not in categorised:
                    categorised[category] = []
                categorised[category].append(spec)
        for category in categories:
            if category not in categorised:
                continue
            wanted = True
            for spec in categorised[category]:
                spec_wanted = False
                if spec['info'] > 0:
                    spec_wanted = True
                if spec['warn'] > 0:
                    spec_wanted = True
                if spec['crit'] > 0:
                    spec_wanted = True
                if spec['emerg'] > 0:
                    spec_wanted = True
                if not spec_wanted:
                    wanted = False
                    break
            if wanted:
                wanted_categories.append(category)
                categorised.pop(category, None)
                continue

        for (category, specs) in categorised.iteritems():
            for spec in specs:
                wanted = False
                if spec['info'] > 0:
                    wanted = True
                if spec['warn'] > 0:
                    wanted = True
                if spec['crit'] > 0:
                    wanted = True
                if spec['emerg'] > 0:
                    wanted = True
                if not wanted:
                    continue
                event = unicode(spec['eventid'])
                for group in self.events[event]['eventgroups']:
                    eventgroups.add(group)

        if len(wanted_categories) == len(self.categories.keys()):
            wanted_categories = [ 'all' ]
        return (wanted_categories, eventgroups)

    def find_alert(self, channels, categories, groups):
        '''
            All we need is an alert condition for NEW EVENTS
            with limit=2 which will trigger for all of the
            categories and groups requested and will send
            to the specified channels.
            It may do more and that's fine.
        '''
        for alert in self.alerts:
            if alert['condition'] != 'NEW EVENTS':
                continue
            if alert['limit'] != 2:
                continue
            ok = True
            for channel in channels:
                if channel not in alert['channel_ids']:
                    ok = False
            for category in categories:
                if category not in alert['categories']:
                    ok = False
            if not ok:
                continue
            for group in groups:
                if group not in alert['eventgroup_ids']:
                    ok = False
            if not ok:
                continue
            return True
        return False

    def create_alert(self, channels, categories, groups):
        self.alert += 1
        name = 'alert%d' % self.alert

        alert = {
            'name': name,
            'condition': 'NEW EVENTS',
            'limit': 2,
            'channel_ids': channels
        }
        if len(categories):
            alert['categories'] = categories
        if len(groups):
            alert['eventgroup_ids'] = list(groups)
        papi.post('3/event/alert-conditions', alert)
        self.load_alerts()

    def copy_rules(self):   
        self.load_notification_settings()
        self.load_channels()
        self.load_alerts()
        self.load_events()
        self.load_eventgroups()

        for _name, settings in self.notifications.iteritems():
            channel_type = settings['type']
            recipients = settings['recipients']
            channels = self.find_channels(channel_type, recipients)
            if channels:
                (categories, groups) = self.notify_on(
                        settings['event_settings'])
                if not self.find_alert(channels, categories, groups):
                    self.create_alert(channels, categories, groups)

    def report_event(self, report, spec):
        flags = ''
        if spec['info'] > 0:
            flags += 'I'
        else:
            flags += '.'
        if spec['warn'] > 0:
            flags += 'W'
        else:
            flags += '.'
        if spec['crit'] > 0:
            flags += 'C'
        else:
            flags += '.'
        if spec['emerg'] > 0:
            flags += 'E'
        else:
            flags += '.'
        report.write("        %s %s\n" % (flags, spec['eventid']))

    def report_categories(self, report, categorised):
        if 0 == len(categorised.keys()):
            return
        for (category, specs) in categorised.iteritems():
            report.write("    Category %s\n" % category)
            for spec in specs:
                self.report_event(report, spec)

    def report_events(self, report, specs):
        if 0 == len(specs):
            return
        report.write("    Events\n")
        for spec in specs:
            self.report_event(report, spec)

    def report(self):
        path = REPORT_FILE
        if not os.path.isdir(REPORT_DIR):
            try:
                os.makedirs(REPORT_DIR)
            except:
                path = '/ifs/notification_configuration.txt'

        with open(path, "w") as report:
            for name, settings in self.notifications.iteritems():
                (categorised, uncategorised) = self.categorise(settings['event_settings'])
                report.write ("%s %s %s\n" % (
                        name,
                        settings['type'],
                        settings['recipients']))
                self.report_categories(report, categorised)
                self.report_events(report, uncategorised)
            report.write("\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n")
        os.system('echo Channels >> %s' % path)
        os.system('echo >> %s' % path)
        os.system('isi event channels list -v >> %s' % path)
        os.system('echo >> %s' % path)
        os.system("echo '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' >> %s" % path)
        os.system('echo Alert Conditions >> %s' % path)
        os.system('echo >> %s' % path)
        os.system('isi event alerts list -v >> %s' % path)

def main():
    node_stat = sysver.Node_Status()
    if node_stat.upgraded_across_riptide():
        alert_cfg = Config('celog.alert')
        reporter_cfg = Config('celog.reporter')
        copier = NotifcationRulesCopier()
        copier.copy_rules()
        copier.report()
        if os.path.exists(OLD_CELOG_DB) and not os.path.exists(ARCHIVE_DB):
            os.rename(OLD_CELOG_DB, ARCHIVE_DB)
        else:
            open(ARCHIVE_DB, 'a').close()

if __name__ == "__main__":
    main()
