#!/usr/bin/env python
# -*- coding: utf-8 -*-

from tcp2canopsis.daemon import run_daemon
from argparse import ArgumentParser
import json
import sys
import os


if __name__ == '__main__':
    parser = ArgumentParser(description='TCP Connector for Canopsis')
    parser.add_argument(
        '-c', '--config',
        nargs=1,
        help='Path to configuration file (optionnal)'
    )
    parser.add_argument(
        '-p', '--port',
        type=int, nargs=1,
        help='Port to listen (required if no config file provided)'
    )
    parser.add_argument(
        '-a', '--amqp',
        nargs=1,
        help='AMQP url to send event (required if no config file provided'
    )
    args = parser.parse_args()

    if args.config is None:
        if args.port is None or args.amqp is None:
            parser.print_usage()
            sys.exit(1)

        port = args.port[0]
        amqp = args.amqp[0]

    else:
        cfgpath = os.path.expanduser(args.config[0])

        try:
            with open(cfgpath) as f:
                config = json.load(f)

            port = int(config['tcp2canopsis']['port'])
            amqp = config['tcp2canopsis']['amqp']

        except IOError as err:
            print('Impossible to open file {0}: {1}'.format(cfgpath, err))
            sys.exit(1)

        except (KeyError, ValueError) as err:
            print('Impossible to parse config {0}: {1}'.format(cfgpath, err))
            sys.exit(1)

    run_daemon(port, amqp)
