#!/usr/bin/env python

USAGE = """Tester to dump pubsub messages from logtrails

Independent dump tool to test messages generated by logtrails to redis pubsub channels.
"""

import redis
import json
import time

from systematic.shell import Script

script = Script()
script.add_argument('-h', '--host', default='localhost', help='Redis hostname')
script.add_argument('-p', '--port', default='6379', help='Redis port')
script.add_argument('channels', nargs='*', help='Channels to dump')
args = script.parse_args()

if args.channels:
    args.channels = [channel for v in args.channels for channel in v.split(',')]
else:
    script.exit(1, 'No channels to monitor provided.')

try:
    r = redis.StrictRedis(host=args.host, port=args.port)
    p = r.pubsub()
    for channel in args.channels:
        p.subscribe(channel)
except Exception as e:
    script.exit(1, 'Error subscribing to redis pubsub channels: {0}'.format(e))

while True:
    try:
        m = p.get_message()
        if m and m['data']:
            try:
                message = json.loads(m['data'])
            except:
                continue
            script.message('{0:12} {1}'.format(m['channel'], json.dumps(message, indent=2)))
        else:
            time.sleep(0.2)
    except Exception as e:
        print e
