#!/usr/bin/env python2
from __future__ import division
import sys
import re
import argparse
from collections import defaultdict

def parse_args():
    parser = argparse.ArgumentParser(
            description='Colorize accesslogs from stdin.\
            Example: tail -f log | %(prog)s')
    parser.add_argument('--user-agent', dest='user_agent',
            action='store_true', default=False, help='Display user-agent.')
    parser.add_argument('--referrer', action='store_true', default=False,
            help='Display referrer.')
    
    return parser


def human_size(size):
    for x in ['B','KB','MB','GB','TB']:
        if size < 1024.0:
            return '{:3.1f}{}'.format(size, x)
        size /= 1024.0


def term_color(num, s):
    return '\033[38;5;{}m{}\033[0m'.format(num, s)


def run(parser):
    if sys.stdin.isatty():
        parser.print_help()
        quit()
    args = parser.parse_args()
    method_colors = {
            'GET': lambda x: term_color(213, x),
            'POST': lambda x: term_color(203, x)
            }
    e = '(.+?)'
    r = re.compile('{0} - {0} \[{0}:{0} {0}\] "(?:(?:{0} {0} {0})|(-))" {0} {0} "{0}" "{0}"'.format(e))

    requests = defaultdict(int)
    total = 0
    ips = defaultdict(int)

    while True:
        s = sys.stdin.readline()
        if not s:
            break
        m = r.match(s)
        if not m:
            continue
        else:
            ip = m.group(1)
            remote_user = m.group(2)
            date = m.group(3)
            time = m.group(4)
            utc = m.group(5)
            http_method = m.group(6)
            uri = m.group(7)
            empty = m.group(8)
            protocol = m.group(9)
            status_code = m.group(10)
            size = {'bytes': int(m.group(11)), 'human': human_size(int(m.group(11)))}
            referrer = m.group(12)
            user_agent = m.group(13)
        
        ip = ip[7:] if ip.startswith('::ffff:') else ip

        total += size['bytes']
        ips[ip] += size['bytes']
        requests['total'] += 1
        requests[status_code] += 1
        
    print 'Number of requests: {}'.format(requests['total'])
    print 'Number of 200 responses: {}'.format(requests['200'])
    print 'Number of 400 responses: {}'.format(requests['400'])
    print 'Bytes served: {}'.format(human_size(total))
    print 'Number of different IP-addresses: {}'.format(len(ips))

if __name__ == '__main__':
    parser = parse_args()
    run(parser)
