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

# Usage: cat <file> | python client.py
# Example line of the input file: 127.0.0.1 20130101
# Note: the last parameter (the day) is optional,
#       the default value is the last imported day
# The output of the script is: 127.0.0.1 3303 20130101

import argparse
import sys


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
            default=sys.stdin)
    parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
            default=sys.stdout)
    parser.add_argument("-d", "--debug", action="store_true",
            help='Enable debug mode (raise an exception if an IP is invalid).')
    args = parser.parse_args()

    import ipasn.redis as ipasn

    if args.debug:
        ipasn.skip_exception = False

    for line in args.infile:
        line = line.strip()
        tmp_line = ''
        if not len(line) > 0:
            continue
        splitted = line.split(' ')
        date = None
        if len(splitted) > 1:
            ip, date = splitted
        else:
            ip = line
        asn = ipasn.asn(ip, date)
        if date is None:
            date = ipasn.get_current_date()
        if asn is not None:
            args.outfile.write('{} {} {}\n'.format(ip, asn, date))
