import os, time, sys
import signal
import mysql.connector

def makefileW(fpath, data):    
    text_file = open(fpath, "w")
    text_file.write(data)
    text_file.close()

def readfile(fpath):
    data = ''
    text_file = open(fpath, "r")
    data = text_file.read()
    text_file.close()
    return data

def clean(*args):
    print "Goodbye!"  
    makefileW("chktkn", "OFF")
    sys.exit()

for sig in (signal.SIGABRT, signal.SIGINT, signal.SIGTERM):
    signal.signal(sig, clean)

if(readfile("chktkn") == "OFF"):
    while True:
        makefileW("chktkn", "ON")
        cnx = mysql.connector.connect(user='sam', password='jigna1234',host='127.0.0.1', database='sam')
        cursor = cnx.cursor()
        test_directory = '.'
        for child in os.listdir(test_directory):
            #test_path = os.path.join(test_directory, child)
            if os.path.isdir(child) and child !='images' and child != 'Twisted-13.2.0':
                for fchild in os.listdir(child+"/sessions/"):          
                  if time.time() - os.stat(child+"/sessions/"+fchild).st_mtime > 90:
                    strdata = readfile(child+"/sessions/"+fchild).split('^')
                    query = "INSERT INTO `strlog`(`uid`, `token`, `ip`, `chnl`, `strtime`, `uagent`) VALUES (%s, %s, %s, %s, %s, %s)"
                    try:
                      cursor.execute(query, (fchild.split('-')[1].replace('.ses',''), fchild.split('-')[0], strdata[1], child, str(time.time()-int(strdata[0])), strdata[3]))
                      cnx.commit()
                    except:pass
                    os.remove(child+"/sessions/"+fchild)
                    print fchild
        cnx.close()
        time.sleep(90)
    
   

        
        
        
