#!/usr/bin/python
# -*- coding: utf-8 -*-  
import time, sys, getopt, os, random

ip = ""
login = "admin"
password = "12345"

def usage():
    print "Usage:\r\n\
        checklogfile.py <filename> - to check local log file\r\n\
        checklogfile.py -d <ip-address> - to download and check log file"


def parse(path):
    f = open(path)
    lines = [line.rstrip('\n') for line in f]
 
    #Remove UTF8 BOM 
    lines[0] = lines[0].replace('\xEF\xBB\xBF','')

    #Remove empty lines
    for i in range(len(lines)-1, len(lines)-10, -1):
        #print "str -", i, lines[-i] 
        if lines[i] == " "*118+"\x0D":
            del lines[i]

    print "len: ", len(lines)
    return lines


def do_login():
        os.system("curl -s -b /tmp/cookies.txt -c /tmp/cookies.txt -d \"login=%s&password=%s\" http://%s/login.cgi > /dev/null" % (login, password, ip))


def log_download(path):
        print "Downloading log file..."
	if 0 == os.system("curl -b /tmp/cookies.txt -c /tmp/cookies.txt \"http://%s/history.cgi?page=all&_=%s\" --output %s --progress" % (ip, random.randint(0, 0xFFFF), path)):
            return True
        else:
            return False


def check(path):
    lines = parse(path)
 
    lastptr = 0
    for i in range(len(lines)):
        #i = lines.index(s)
        s = lines[i]
        print "\rProcessing: %d%%" %( (i+1)*100/len(lines)),

        #Check if string in valid format
        if len(s) > 119 or s[0] != '"' or s.count('"') != 2 or s.count('\x00') != 0:
            print "\nError. Log file is corrupted:"
            print "Wrong string (at index %d) : %s" %(i+1, s)
            return False

        strdate = s.replace('"','').split(";")[3].rstrip()
        #print strdate
        newdate = time.strptime(strdate, "%d.%m.%y %H:%M:%S")
        if i != 0:
            if newdate < lastdate:
                if lastptr == 0:
                    lastptr = i+1
                else:
                    print "\nError. Wrong message order!"
                    print "Look at index:", i+1 
 
        lastdate = newdate        
   
    print "\nLast message index:", lastptr
    print "Log file is OK"
    return True

        
def main():
    global ip

    try:
        opts, args = getopt.getopt(sys.argv[1:], "hd:", \
                ["help", "download="])
    except getopt.GetoptError:
        usage()
        sys.exit(2)
    
    for opt, arg in opts:
        if opt in ("-h", "--help"):
                usage()
                sys.exit()
        if opt in ("-d", "--download"):
                ip = arg

    if ip == "" and len(sys.argv) < 2:
        usage()
        sys.exit(2)

    if ip == "": 
        path = sys.argv[-1]
    else:
        path = "/tmp/checklog.csv"
        do_login()
        if not log_download(path):
            print "Download error"
            sys.exit(2)
    
    check(path)


if __name__ == "__main__":
    main()

