#!/usr/bin/env python
import os
import re, sre_constants
import sys
from pipe import * # http://pypi.python.org/pypi/pipe/1.3

if len(sys.argv) < 3:
    print "grep: Grep dans les logs de quelqu'un"
    print "N'a besoin que d'une partie de son nom pour le retrouver"
    print "Usage: grep USERNAME SEARCH"
    print "Exemple: grep shaz b[iy]te"
    print "         grep CaptSea .*"
    sys.exit(0)

who = sys.argv[1]
search = ' '.join(sys.argv[2:])

try:
    lines = os.listdir('logs/users') \
        | where(lambda user: re.search(who, user, re.IGNORECASE) is not None) \
        | select(lambda user: open('logs/users/%s' % user) \
                     | where(lambda line: re.search(search, ' '.join(line.split()[4:]), re.IGNORECASE) is not None) \
                     | select(lambda line: line.split(None, 4)) \
                     | where(lambda line: len(line) == 5) \
                     | select(lambda line: "%s %s <%s> %s" % (line[0], line[1], user, line[4]))) \
                     | traverse | sort | tail(6)
except sre_constants.error as e:
    print e
else:
    for line in lines:
        print line,
