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

import argparse
import signal
from pubsublogger import subscriber


def signal_handler(signal, frame):
    if subscriber.pubsub is not None:
        subscriber.stop()
        print "Subscriber closed."

signal.signal(signal.SIGINT, signal_handler)

if __name__ == '__main__':

    parser = argparse.ArgumentParser(description='Configure a logging subscriber.')

    parser.add_argument("-H", "--hostname", default='localhost',
            type=str, help='Set the hostname of the server.')
    parser.add_argument("-p", "--port", default=6379,
            type=int, help='Set the server port.')
    parser.add_argument('-s', '--use_unix_socket',  action='store_true',
            help='Use a unix socket path instead of a tcp socket.')
    parser.add_argument("--unix_socket_path", default='/tmp/redis.sock',
            type=str, help='Unix socket path.')
    parser.add_argument("-c", "--channel",
            type=str, required=True, help='Channel to subscribe to.')
    parser.add_argument("-l", "--log_path",
            required=True, help='Path where the logs will be written')
    parser.add_argument("-d", "--debug", action="store_true",
            help='Also log debug messages.')
    parser.add_argument("-m", "--mail", type=file, default=None,
            help='Path to the config file used to send errors by email.')

    args = parser.parse_args()

    if args.use_unix_socket:
        subscriber.unix_socket = args.unix_socket_path
    else:
        subscriber.hostname = args.hostname
        subscriber.port = args.port
    subscriber.run(args.channel, args.log_path, args.debug, args.mail)