#!/usr/bin/python
import ConfigParser
import json
import logging
from logging.handlers import SysLogHandler
import os
import signal
import sys

import argparse
import fedmsg

import fedwatch

log = logging.getLogger()

def configure_logger():
    formatter = logging.Formatter('%(module)s - %(levelname)s - %(message)s')
    sl = SysLogHandler('/dev/log', facility=SysLogHandler.LOG_USER)
    sl.setFormatter(formatter)

    log.addHandler(sl)
    return log

def convert_config(config_file, scp):
    confdict = {}
    for section in scp.sections():
        alist = []
        for key, arg in scp.items(section):
            alist.append(arg)
        confdict[section] = {'args':alist}
    try:
        cf = open(config_file, "w")
        try:
            json.dump(confdict, cf, indent=4)
        finally:
            cf.close()
    except IOError, e:
        log.error("conversion of configuration failed: {e}".format(
            e=e))
        sys.exit(1)



def read_config(config_file):
    scp = ConfigParser.SafeConfigParser()
    confdict = {}
    try:
        scp.read(config_file)
        log.warning("converting configuration {conf} to json format".format(
            conf=config_file))
        convert_config(config_file, scp)
    except ConfigParser.MissingSectionHeaderError, e:
        # happens when file is already converted
        pass

    try:
        cf = open(config_file, "r")
        try:
            confdict = json.load(cf)
        finally:
            cf.close()
    except IOError, e:
        log.error("loading of configuration failed: {e}".format(
            e=e))
        sys.exit(1)
    return confdict

def termhandler(signum, frame):
    log.info("received SIGTERM. Closing shop.")
    raise SystemExit("received SIGTERM. Closing shop")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Run tasks on fedmsg changes',
				     formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('--config-file', '-c', default='/etc/fedwatch.conf',
                        help='Configuration file for topic selection and data mapping')
    parser.add_argument('--script-dir', '-s', default='/etc/fedwatch.d',
                        help='Directory with scripts to run for fedmsg messages')
    parser.add_argument('--version', '-v', action='store_true',
                        help='Run with debug output')
    parser.add_argument('--debug', '-d', action='store_true',
                        help='Run with debug output')

    args = parser.parse_args()
    if args.version:
        print(fedwatch.__version__)
        sys.exit(0)
    confdict = read_config(args.config_file)
    configure_logger()

    if args.debug:
        log.setLevel(logging.DEBUG)
    if not os.path.isdir(args.script_dir):
        parser.error("script directory {d} is missing".format(d=args.script_dir))
    log.info("started")
    signal.signal(signal.SIGTERM, termhandler)
    try:
        log.debug("configuration dict: {conf}".format(conf=confdict))
        fw = fedwatch.FedWatch(confdict, args.script_dir)
        fw.watch()
    except KeyboardInterrupt:
        log.info("finishing up")
    except Exception, e:
        log.exception("runtime exception: {e}".format(e=e))
