#!/usr/bin/env python

"""
pystogram -- Display time-series histograms of Apache-style log files on the command-line.

    $ pystogram /var/log/access.log
    2012-07-16 01  **                                                         1493
    2012-07-16 02  ***                                                        2819
    2012-07-16 03  *******                                                    5753
    2012-07-16 04  **********                                                 7721
    2012-07-16 05  *******************                                       14833
    2012-07-16 06  **************************                                19914
    2012-07-16 07  **********************************                        25626
    2012-07-16 08  *****************************************************     39901
    2012-07-16 09  *******************************************************   40943
    2012-07-16 10  *************************************************         36690
    2012-07-16 11  ********************************************              32967
    2012-07-16 12  **************************************                    28989
"""

import datetime
import fileinput
import re
import time

from pystogram.console import AsciiChart
from pystogram.dateutil import MONTHS
from pystogram.histogram import Histogram


# FIXME: Make the regex configurable: strptime format string --> regex
TIMESTAMP_REGEX = re.compile(
    r' \[(?P<day>\d{2})/(?P<month>\w{3})/(?P<year>\d{4}):'
    r'(?P<hour>\d{2}):(?P<minute>\d{2}):(?P<second>\d{2})(?P<offset>\s?(\+|-)\d+)?\] '
)

def get_timestamp(line):
    match = TIMESTAMP_REGEX.search(line)
    if match:
        # FIXME: Parse the timestamp with time.strptime()
        return time.struct_time(sequence=(int(match.group('year')),
                                          MONTHS[match.group('month')],
                                          int(match.group('day')),
                                          int(match.group('hour')),
                                          int(match.group('minute')),
                                          int(match.group('second')),
                                          0, 0, 0))[0:6]

def main():
    histogram = Histogram()

    for line in fileinput.input():
        timestamp = get_timestamp(line)
        if timestamp is not None:
            histogram.count(timestamp)

    # FIXME: Allow width to be specified on command-line
    chart = AsciiChart(histogram)
    # FIXME: Allow resolution to be specified on command line
    chart.draw()

if __name__ == '__main__':
    main()
