#!/usr/bin/python3.8
# -*- coding: utf-8 -*-
#from Crypto.Cipher import AES
from subprocess import Popen, PIPE, CalledProcessError
#import StringIO
import time,random
import subprocess
import threading
import os,sys
#import pyinotify
import xml.dom.minidom
import codecs
#import psycopg2
from threading import Thread
import datetime
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from threading import Thread, Lock
import psutil
MelChioR='GSDGJSVPIGJVGBJPOGJPJGPGJPSP11VSEGTSBSSVVDVSVDG353553BDBHYFHDJHDIHTHBYHDHYYHYDHYDD'    
ElGrandeMatadoR='HY6YYHTD8HN68DFY48HYRH74T876H4DR3H43HGGJJ8Y8TY4D34GHR8RY38FYH4348RHDRFDV5843YH4374YH874DTY38H4DY384R3D8H4DY34D3K84OU8HL45843Q84AG84AZ84RFTHDFY38JU4834FKU4K4K8ULO4Y3RY13DET463J434JR3T84J43I6U87KL4Y38937TR94R3J8448K3R864783R684786I438'
ElCondoR='4YBD3H4DERRTYTYYH834DFHY384H7HDFY384HDFY84GUH3HYF3JH4JY3O8L43H843V8FY4VD84D384H3V8UT4K3B1T3BK43F8K43I84N54V38D8FY789EY874DY1HC836168H46UI4OGM6I84FCD6T8C4X6ER46SG84TY686TY4GHVSRHY46CRY8HC6Y87468RSX4XS84SEG7BV76F8JU4IUL86OM486I4GJUV864F86DYT4C6'
ElMatadoR='HY68HYHTYN68DFY48HTYHTHYYRH74T876H4DR3H438DDSDY8TY4D34GHR8RY38FYH4348RHDR843YH4374YH874DTY38H4DY384R3D8H4DY34D3K84OU8HL45843Q84AG84AZ84RFTHDFY38JU4834FKU4K4K8ULO4Y3RY13DET463J434JR3T84J43I6U87KL4Y38937TR94R3J8448K3R864783R684786I438'
def ElBrassoR():
    global ElChaloR
    ElChaloR=MelChioR[4:6]+ElGrandeMatadoR[8:10]+ElCondoR[18:20]+ElMatadoR[11:13]+MelChioR[5:7]+ElCondoR[20:22]+ElGrandeMatadoR[25:27]+ElCondoR[28:30]+ElMatadoR[17:19]+ElGrandeMatadoR[21:23]+MelChioR[12:14]+ElMatadoR[30:32]
ElBrassoR()
jak='2164691737824342'
encodings={}
i=1
oscdir=os.curdir
for arg in sys.argv:
    if int(i)==2:
        verbose=arg
        if str(verbose)=='-v':
            print (str(verbose))
    if int(i)==3:
        alls=arg
        if str(verbose)=='-v':
            print (str(alls))
        allt=alls
    if int(i)==4:
        acto=arg
        if str(verbose)=='-v':
            print (str(acto))
        action=acto
    if int(i)==5:
        mlts=arg
        if str(verbose)=='-v':
            print (str(mlts))
        mlt=mlts
    if int(i)==6:
        malt=arg
        if str(verbose)=='-v':
            print (str(malt))
        mailto=malt
    if int(i)==7:
        filev=arg
        if str(verbose)=='-v':
            print ('file:'+str(filev))
        file=filev
    i=i+1
try:
    encodings["Process","Active"]=False
    encodings["Files","Active"]=False
    encodings["Title","Active"]=False
    encodings["Process1"]=""
    encodings["Process1",'alias']=""
    encodings["Process1",'language']=""
    encodings["Process2"]=""
    encodings["Process2",'alias']=""
    encodings["Process2",'language']=""
    encodings["Files1"]=""
    encodings["Files1",'alias']=""
    encodings["Files1",'language']=""
    encodings["Files2"]=""
    encodings["Files2",'alias']=""
    encodings["Files2",'language']=""
    encodings["Title1"]=""
    encodings["Title1",'alias']=""
    encodings["Title1",'language']=""
    encodings["Title2"]=""
    encodings["Title2",'alias']=""
    encodings["Title2",'language']=""
    encodings["Title3"]=""
    encodings["Title3",'alias']=""
    encodings["Title3",'language']=""
    TchemFSF=oscurdir+os.sep+'conf'+os.sep+'languages.gwh'
    isconfig=os.path.isfile(TchemFSF)
    if isconfig==True:
        fft=open(TchemFSF, mode ='rb')
        output = StringIO.StringIO(fft.read())
        decoutput=StringIO.StringIO()
        fft.close()
        Gdecrypt(output,decoutput)
        lines={}
        p=0
        lines = decoutput.getvalue()

        for char in lines:
            if char=='\t':
                p+=1
                continue
            if char=='\n':
                glorb=True
                break
            if p==0:
                encodings["Process1"]=str(encodings["Process1"])+str(char)
                encodings["Process","Active"]=True
            if p==1:
                encodings["Process2"]=str(encodings["Process2"])+str(char)
                encodings["Process","Active"]=True
            if p==2:
                encodings["Files1"]=str(encodings["Files1"])+str(char)
                encodings["Files","Active"]=True
            if p==3:
                encodings["Files1"]=str(encodings["Files1"])+str(char)
                encodings["Files","Active"]=True
            if p==4:
                encodings["Title1"]=str(encodings["Title1"])+str(char)
                encodings["Title","Active"]=True
            if p==5:
                encodings["Title2"]=str(encodings["Title2"])+str(char)
                encodings["Title","Active"]=True
            if p==6:
                encodings["Title3"]=str(encodings["Title3"])+str(char)
                encodings["Title","Active"]=True
        decoutput.close()
        output.close()


except:
    encodings["Process1"]=sys.getdefaultencoding()
    encodings["Process1",'alias']=""
    encodings["Process1",'language']="workstation system encoding"
    encodings["Process2"]=""
    encodings["Process2",'alias']=""
    encodings["Process2",'language']=""
    encodings["Files1"]=sys.getdefaultencoding()
    encodings["Files1",'alias']=""
    encodings["Files1",'language']="workstation system encoding"
    encodings["Files2"]=""
    encodings["Files2",'alias']=""
    encodings["Files2",'language']=""
    encodings["Title1"]=sys.getdefaultencoding()
    encodings["Title1",'alias']=""
    encodings["Title1",'language']="workstation system encoding"
    encodings["Title2"]=""
    encodings["Title2",'alias']=""
    encodings["Title2",'language']=""
    encodings["Title3"]=""
    encodings["Title3",'alias']=""
    encodings["Title3",'language']=""
#if postgres
##conn_string = "host='"+str(serverip)+"' dbname='chronos-monitor.com' user='chronos' password='gortex855'"
##connec = psycopg2.connect(conn_string)
##connec.set_client_encoding('UTF8')
##cursex = connec.cursor()
class minuteView(Thread):
    global cursex,connec,user,poste,serverip,fanal,rept
    def __init__(self,resac):
        Thread.__init__(self)
        self.setDaemon(1)
        self.resac=resac
        self.start()
    def run(self):
        global cursex,connec,user,poste,fanal,rept
        def unchain(string):
            result=""
            if string:
                x=len(string)            
                for x in range(0,x):
                    if string[x] in ["'",'"']:
                        result=result+" "
                    elif string[x] in ["#"]:
                        pass
                    else:result=result+string[x]
            return result


        def chain(string):
            results=""
            if string:
                x=len(string)            
                for x in range(0,x):
                    if string[x]in ["\\"]:results=results+string[x]+string[x]
                    else:results=results+string[x]
            return results
        def formatFanal():
            global fanal
            fanal['client']="None"
            fanal['prestation']="None"

        #print 'good'
        Txzorbl={}
        final={}
        fanal={}
        #formatFanal()
        ses=0
        p=0
        Txzorbl[p]=""
        string=str(self.resac)
        ln=len(string)
        for x in range(0,ln):
            char=string[x:x+1]
            if char=="#":
                p+=1
                Txzorbl[p]=""
            else:
                Txzorbl[p]=Txzorbl[p]+char
        try:
            #print 'minute view1'
            hour=Txzorbl[1]
            dateprem=hour[0:8]
            date='20'+dateprem[6:8]+'/'+dateprem[0:2]+'/'+dateprem[3:5]
            houre=hour[9:18]
            procs=""
            chemin=""
            fen=""
            ncl=0
            #print 'must'
            datour=str(Txzorbl[1]) 
            inscript=False
            #print 'minutevie2'
            #if self.type=="full":
            intostr="""INSERT INTO logfull (file,line,date, heure, nomfenetre, processus, chemin, clicks, client,activite,action,userid,posteid,final_userid) VALUES """
                #sfile=ffile
            #elif self.type=="condensed":
                #intostr="""INSERT INTO logcondensed (file,line,date, heure, nomfenetre, processus, chemin, clicks, client,activite,action,userid,posteid,final_userid) VALUES """
                #sfile=cfile
            #print 'minute view3'
           #     print 'inT'
            chemin=Txzorbl[4]
            action=Txzorbl[2]
            line=Txzorbl[0]
            userid=unchain(Txzorbl[6])
            postepid=unchain(Txzorbl[7])
            action_process=unchain(Txzorbl[3])
            procs=chain(unchain(Txzorbl[5]))
            print (str(procs))
            i=len(rept)
            for char in rept:
                if str(char)=='/':
                    sfile=""
                    continue
                if str(char)=='.':
                    break
                else:
                    sfile=str(sfile)+str(char)
            formatFanal()
            #if analyse==True:
             #   analyseFichier(chemin)
            chemin=chain(unchain(Txzorbl[4]))
            fen=chemin
            intostr=intostr+"('"+str(sfile)+"','"+ line+"','"+ date+"','" +houre+"','"+ fen+"','"+ action_process+"','"+chemin+"','"+str(ncl)+"','"+fanal['client']+"','"+fanal['prestation']+"','"+str(action)+"','"+user+"','"+poste+"','"+poste_adminid+"');"    
            inscript=True
            #print 'good2'
        #    print 'miuteview7'
            if inscript==True:
##                    conn_string = "host='"+str(users['serverip'])+"' dbname='chronos-monitor.com' user='chronos' password='gortex855'"
##                    conn = psycopg2.connect(conn_string)
##                    conn.set_client_encoding('UTF8')
##                    curs = conn.cursor()
##                    presult=curs.execute("SELECT action FROM logview WHERE userid='"+userid+"';")
##                    rresult=curs.fetchone()
##                    if rresult:
##                        intostr="UPDATE logview SET date='"+str(date)+"', heure='" +str(houre)+"', nomfenetre='"+ fen+"', processus='"+ procs+"', chemin='"+chemin+"', clicks='"+str(ncl)+"', client='',activite='',action='"+str(action)+"',posteid='"+str(poste['PID'])+"',final_userid='"+poste['ADMINID']+"' WHERE userid='"+str(userid)+"';"
                result=cursex.execute(intostr)
                connec.commit()
                #print 'hmmm'

           #     print 'good'
##                    curs.close()
##                    conn.close()
        except:
            pass
         #   print 'error'


def Gdecrypt(outputin,result):
    xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
    chunksize=(64*1024)
    rep=''
    while True:
        chunk=''
        chunk=outputin.read(n=chunksize)
        if len(chunk)==0:
            break
        elif len(chunk)%16!=0:
            chunk += ' ' * (16-len(chunk) % 16 )
        rep=rep+xdecryptor.decrypt(chunk)
    logfile.close()
    result.write(rep)
    return result
def startX():
    global ElChalor,jak,rept
##    today = date.today()
##    ts = time.time()
##    sts=str(ts).replace('.', '')
##    zrept=oscurdir+os.sep+'wok'+os.sep+'need'+os.sep+'zero.gwh'
##    rept=oscurdir+os.sep+'wok'+os.sep+'need'+os.sep+'file_access'+str(today)+'_'+str(sts)+'.gwh'
##    logfileT = open(zrept, mode ='rb')
    logfile=open(rept, mode ='rb')
    def Gdecrypt(outputin,result):
        xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
        chunksize=(64*1024)
        rep=''
        while True:
            chunk=''
            chunk=outputin.read(n=chunksize)
            if len(chunk)==0:
                break
            elif len(chunk)%16!=0:
                chunk += ' ' * (16-len(chunk) % 16 )
            rep=rep+xdecryptor.decrypt(chunk)
        logfile.close()
        result.write(rep)
        return result
                
    outputin = StringIO.StringIO(logfile.read())
##                        outputin.write(logfile.read())
    result = StringIO.StringIO()
    #detr=obj.decrypt(outputin.getvalue())
    Gdecrypt(outputin,result)
    #result.write(detr)
    drunk=result.getvalue()
    #print repr(drink)
    xim=xml.dom.minidom.parseString(drunk)
##            zrept=oscurdir+os.sep+'wok'+os.sep+'need'+os.sep+'zero.xml'
##            logfile = open(zrept, mode ='r')
##            xim =xml.dom.minidom.parse(logfile)
##            logfile.close()
    return xim
def createrept():
    global period,oscurdir,rept,sts
    try:
        now = datetime.datetime.now()
        if str(period)=="m":
            sts=str(now.hour)+'_'+str(now.minute)
        else:
            sts=str(now.hour)
        zrept=oscurdir+os.sep+'need'+os.sep+'zero.gwh'
        rept=oscurdir+os.sep+'enc'+os.sep+'file_access'+str(now.year)+'-'+str(now.month)+'-'+str(now.day)+'_'+str(sts)+'.gwh'
        logfileTH = open(zrept, mode ='rb')
        with open(rept, "wb") as binary_file:
            binary_file.write(logfileTH.read())
        logfileTH.close()
    except:
        return False
    return True
def startX1():
    global ElChalor,jak,sts,period,rept,oscurdir,rept
    zrept=oscurdir+os.sep+'need'+os.sep+'zero.gwh'
    logfileT = open(zrept, mode ='rb')
    with open(rept, "wb") as binary_file:
        binary_file.write(logfileT.read())
    def Gdecrypt(outputin,result):
        xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
        chunksize=(64*1024)
        rep=''
        while True:
            chunk=''
            chunk=outputin.read(n=chunksize)
            if len(chunk)==0:
                break
            elif len(chunk)%16!=0:
                chunk += ' ' * (16-len(chunk) % 16 )
            rep=rep+xdecryptor.decrypt(chunk)
        result.write(rep)
        return result
                
    outputin = StringIO.StringIO(logfileT.read())
##                        outputin.write(logfile.read())
    result = StringIO.StringIO()
    #detr=obj.decrypt(outputin.getvalue())
    Gdecrypt(outputin,result)
    #result.write(detr)
    drunk=result.getvalue()
    #print repr(drink)
    xim=xml.dom.minidom.parseString(drunk)
    logfileT.close()
##            zrept=oscurdir+os.sep+'wok'+os.sep+'need'+os.sep+'zero.xml'
##            logfile = open(zrept, mode ='r')
##            xim =xml.dom.minidom.parse(logfile)
##            logfile.close()
    return xim
def loadlog():
    global XTstring
    XTstring=startX()
    #print repr(drink)
def TSave():
    global XTstring,XCstring,rept
    def Gencrypt(results,outputfile):
        encryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
        #decryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
        chunksize=(64*1024)
        mlogfile = open(outputfile, 'wb')
        ret=''
        while True:
            chunk = results.read(n=chunksize)
            if len(chunk)==0:
                break
            elif len(chunk)%16!=0:
                chunk += ' ' * (16-len(chunk) % 16 )                
            ret=ret+chunk
        djunky=encryptor.encrypt(ret)
        mlogfile.write(djunky)
        mlogfile.close()
    class TTransPak:
        def write(self,data):
            outputin.write(data.encode('utf-8'))
    outputin = StringIO.StringIO()
    XTstring.writexml(TTransPak(), encoding='utf-8')
    results = StringIO.StringIO(outputin.getvalue())        
    Gencrypt(results,rept)
    outputin.close()
    results.close()


def Twrite(string):
    global rept,XTstring,syncrotip,sts,period,fl
    now = datetime.datetime.now()
    if str(period)=="m":
        msts=str(now.hour)+'_'+str(now.minute)
    else:
        msts=str(now.hour)
    if str(sts)!=str(msts):
        mes=createrept()
        fl=0
        XTstring=xml.dom.minidom.parseString('<PrsPC></PrsPC>')
    else:
        loadlog()
    try:
        racine=XTstring.documentElement
        element =XTstring.createElement("PrsP")
        element.setAttribute('ReportLine',string)
        racine.appendChild(element)
        TSave()
    finally:
        if syncrotip=='cont':
            minuteView(string)

def unchain(string):
    result=""
    if string:
        x=len(string)            
        for x in range(0,x):
            if string[x] in ["'",'"']:
                result=result+" "
            elif string[x] in ["#"]:
                pass
            else:result=result+string[x]
    return result
##class EventProcessor(pyinotify.ProcessEvent):
##    _methods = ["IN_CREATE",
##                "IN_OPEN",
##                "IN_ACCESS",
##                "IN_ATTRIB",
##                "IN_CLOSE_NOWRITE",
##                "IN_CLOSE_WRITE",
##                "IN_DELETE",
##                "IN_DELETE_SELF",
##                "IN_IGNORED",
##                "IN_MODIFY",
##                "IN_MOVE_SELF",
##                "IN_MOVED_FROM",
##                "IN_MOVED_TO",
##                "IN_Q_OVERFLOW",
##                "IN_UNMOUNT",
##                "default"]

def process_generator(cls, method):
    pass
##    global rept
##    def _method_name(self, event):
##        global rept,resac,fl
##        def openlog():
##            global rept
##            logfile = open(rept, mode ='rb')
##            def Gdecrypt(outputin,result):
##                xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
##                chunksize=(64*1024)
##                rep=''
##                while True:
##                    chunk=''
##                    chunk=outputin.read(n=chunksize)
##                    if len(chunk)==0:
##                        break
##                    elif len(chunk)%16!=0:
##                        chunk += ' ' * (16-len(chunk) % 16 )
##                    rep=rep+xdecryptor.decrypt(chunk)
##                logfile.close()
##                result.write(rep)
##                return result
##                        
##            outputin = StringIO.StringIO(logfile.read())
####                        outputin.write(logfile.read())
##            result = StringIO.StringIO()
##            #detr=obj.decrypt(outputin.getvalue())
##            Gdecrypt(outputin,result)
##            #result.write(detr)
##            drunk=result.getvalue()
##            return drunk
##
##        def flsearch():
##            logln=openlog()
##            result=0
##            listreport={}
##            if logln:
##                x=len(logln)
##                find=False
##                z=1
##                for u in range(0,x):
##                    if logln[u:u+11]=='ReportLine=':
##                        listreport[z]=int(u)+11
##                        listreport['total']=z
##                        z=z+1
##                        find=True
##                        result=""
##                        next
##                if find==True:
##                    for u in range(listreport[listreport['total']],x):
##                        if logln[u]=='#':
##                            find=False
##                            break
##                        elif logln[u] in ['"']:
##                            next
##                        else:
##                            result=result+logln[u]
##                
##            return int(result)
##        fl=flsearch()
##        if str(verbose)=='-v':print (fl)
##            #self.dc.DrawBitmap(self.syncf, 51, 168, True)
##
##        #print "Method name: process_"+str(method)+"\n"+"Path name: "+event.pathname+"\n"+"Event Name:"+event.maskname+"\n"
##
####                  #
####                  # ReadDirectoryChangesW takes a previously-created
####                  #  handle to a directory, a buffer size for results,
####                  #  a flag to indicate whether to watch subtrees and
####                  #  a filter of what changes to notify.
####                  #
####                  # NB Tim Juchcinski reports that he needed to up
####                  #  the buffer size to be sure of picking up all
####                  #  events when a large number of files were
####                  #  deleted at once.
####                  #
####                  results = win32file.ReadDirectoryChangesW (
####                    hDir,
####                    1024,
####                    True,
####                    win32con.FILE_NOTIFY_CHANGE_FILE_NAME |
####                     win32con.FILE_NOTIFY_CHANGE_DIR_NAME |
####                     win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES |
####                     win32con.FILE_NOTIFY_CHANGE_SIZE |
####                     win32con.FILE_NOTIFY_CHANGE_LAST_WRITE |
####                     win32con.FILE_NOTIFY_CHANGE_SECURITY,
####                    None,
####                    None
####                  )
####                  for action, file in results:
##        timec=time.strftime('%m/%d/%y %H:%M:%S')
####                    try:
####                        hwnd = win32gui.GetForegroundWindow()
####                        # we want the desktop window
####                        objid = pyAA.Constants.OBJID_WINDOW
####                        # get the object
####                        ao = pyAA.AccessibleObjectFromWindow(hwnd, objid)
####                        pr= ao.GetProcessAndThreadID()
####                        p = psutil.Process(pr[0])
####                        processactif=p.exe
####                    except:
####                        processactif="None"
##        try:
##            command = "xprop -root _NET_ACTIVE_WINDOW"                                       
##            output = subprocess.Popen(["/bin/bash", "-c", command], stdout=subprocess.PIPE)
##            frontmost = output.communicate()[0].decode("utf-8").strip().split()[-1]
##            fixed_id = frontmost[:2]+"0"+frontmost[2:]
##            command = "wmctrl -lp"
##            output = subprocess.Popen(["/bin/bash", "-c", command], stdout=subprocess.PIPE)
##            window_list = output.communicate()[0].decode("utf-8")
##            window_name = [l for l in window_list.split("\n") if fixed_id in l][0].split(socket.gethostname()+" ")[-1]
##            fen1= window_name
##            print str(fen1)
##        except:
##            fen1="None"
##        try:
##            w_id = subprocess.check_output(["xdotool", "getactivewindow"]).decode("utf-8")
##            name = subprocess.check_output(["xprop", "-id", w_id, "WM_CLASS"]).decode("utf-8").strip()
##            processactif= name
##        except:
##            processactif= "None"
##        full_filename = unchain(processactif)
##        try:
##            if encodings["Process1"]!="":
##                pencod=encodings["Process1"]
##                try:
##                    tprocess=processactif.decode(pencod)
##                except:
##                    try:
##                        if encodings["Process2"]!="":
##                            pencod=encodings["Process2"]
##                            tprocess=processactif.decode(pencod)
##                        else:
##                            pencod='utf-8'
##                            tprocess=processactif.decode(pencod)
##                    except:
##                        pencod='utf-8'
##                        tprocess=processactif.decode(pencod)
##                        
##            else:
##                pencod=sys.getdefaultencoding()
##                tprocess=processactif.decode(pencod)
##
##        except:
##            pencod=sys.getdefaultencoding()
##            tprocess=processactif.decode(pencod)
##        try:
##            full_filenamer=unchain(full_filename)
##            if encodings["Files1"]!="":
##                fencod=encodings["Files1"]
##                try:
##                    full_filename=full_filenamer.decode(fencod)
##                except:
##                    try:
##                        if encodings["Files2"]!="":
##                            fencod=encodings["Files2"]
##                            full_filename=full_filenamer.decode(pencod)
##                        else:
##                            pencod='utf-8'
##                            full_filename=full_filenamer.decode(fencod)
##                    except:
##                        pencod='utf-8'
##                        full_filename=full_filenamer.decode(fencod)
##                        
##            else:
##                fencod=sys.getdefaultencoding()
##                full_filename=full_filenamer.decode(fencod)
##
##        except:
##            pencod=sys.getdefaultencoding()
##            full_filename=full_filenamer.decode(fencod)
##        fl=int(fl)+1
##        resac=str(fl)+'#'+str(timec)+'#'+method+'#'+str(_method_name.__name__)+'#'+full_filename+'#'+unchain(tprocess)+'#'+str(user)+'#'+str(poste)+'\n'
##        #self.Twrite(resac)
##        Twrite(resac)
##        #print full_filename + ACTIONS.get (action, "Unknown") + processactif
##        minuteView(resac)
##        if str(verbose)=='-v':print str(method)
##        if str(verbose)=='-v':print str(full_filename)
##        if str(verbose)=='-v':print str(_method_name.__name__)
##    _method_name.__name__ = "process_{}".format(method)
##    setattr(cls, _method_name.__name__, _method_name)
##
##    def run(self):
##        global oscdir
fl=0
def get_main_dir():
    try:
        sys.frozen
    except AttributeError:
        path = sys.argv[0]
    else:
        path = sys.executable
    return os.path.dirname(os.path.abspath(path))

oscurdir1=get_main_dir()
i=len(oscurdir1)
oscurdir=""
torgol=False
#print (oscurdir1)
if torgol==False:
    oscurdir=oscurdir1
##if str(oscurdir)=="":
##    oscurdir="/var/www/wim-linux/hdom/"
mes=createrept()
if mes==False:
    print ('erreur repertoire')
##try:
##    chemFS= oscdir + os.sep + "conf"+os.sep+"resap.gwh"
##    isdos=os.path.isfile(chemFS)
##    if isdos==True:
##        logfile = open(chemFS,'rb')
##    else:
##        chemFS= oscdir +os.sep+ "need"+os.sep+"zero.gwh"
##        logfile = open(chemFS,'rb')
##except:
##    chemFS= oscdir + os.sep+ "need"+os.sep+"zero.gwh"
##    logfile = open(chemFS,'rb')
##outputin = StringIO.StringIO(logfile.read())
####                        outputin.write(logfile.read())
##result = StringIO.StringIO()
###detr=obj.decrypt(outputin.getvalue())
##Gdecrypt(outputin,result)
###result.write(detr)
##drunk=result.getvalue()
##dossier={}
##xim=xml.dom.minidom.parseString(drunk)
##logfile.close()
##racine=xim.documentElement
##unem = xim.getElementsByTagName('DIR')
##x=1
##for method in EventProcessor._methods:
##    process_generator(EventProcessor, method)
##
##watch_manager = pyinotify.WatchManager()
##event_notifier = pyinotify.Notifier(watch_manager, EventProcessor())

#dossier['nombre']=0
##h=subprocess.PIPE
##print (str(oscurdir))
rga = oscurdir+os.sep+'conf/paths_or_files.txt'
lgac = os.stat(rga).st_size
Ficap = open(rga, mode ='r')
posac=0
n=0
conf={}
while posac < lgac:             
        ChaC = Ficap.readline()
        conf["dir",n]=""
        conf["method",n]=""
        conf["action",n]=""
        conf["arguments",n]=""
        find=False
        tfind=False
        ttfind=False
        hfind=False
        for char in str(ChaC):
            #print (str(char))
            if str(char)==" ":
                if find==True:
                    hfind=True
                find=True
                if ttfind==False:
                    continue
            if char=='\n':
                find=False
                tfind=False
                ttfind=False
                hfind=False
                continue
            if str(char)==':':
                if tfind==True:
                    ttfind=True
                tfind=True
                continue
            if find==False and tfind==False and ttfind==False and hfind==False:
                conf["dir",n]=conf["dir",n]+char
            if tfind==True and ttfind==False and hfind==False and find==True:
                conf["method",n]=conf["method",n]+char
            if ttfind==False and hfind==True:
                conf["action",n]=conf["action",n]+char
            if ttfind==True and hfind==True and tfind==True:
                conf["arguments",n]=conf["arguments",n]+char
        conf["nombre"]=n
##        try:
##            print(str(conf["dir",n]))
##        except:
##            pass
##        try:
##            print('method:'+str(conf["method",n]))
##        except:
##            pass
##        try:
##            print('action:'+str(conf["action",n]))
##        except:
##            pass
##        try:
##            print('arguments:'+str(conf["arguments",n]))
##        except:
##            pass
##        try:
##            print (str(conf["dir",n])+' '+str(conf["method",n])+' '+str(conf["action",n])+' '+conf["arguments",n])
##        except:
##            pass
        n+=1
        posac=Ficap.tell()
rga = oscurdir+os.sep+'conf/conf_email.txt'
lgac = os.stat(rga).st_size
Ficap = open(rga, mode ='r')
posac=0
n=0
confemail={}
confemail["from"]=""
confemail["smtp"]=""
confemail["login"]=""
confemail["password"]=""
while posac < lgac:             
        ChaC = Ficap.readline()
        n+=1
        for char in str(ChaC):
            if n==1:
                confemail["from"]=confemail["from"]+char
            if n==2:
                confemail["smtp"]=confemail["smtp"]+char
            if n==3:
                confemail["login"]=confemail["login"]+char
            if n==4:
                confemail["password"]=confemail["password"]+char
        posac=Ficap.tell()
##try:
##    print('from'+str(confemail["from"]))
##except:
##    pass
##try:
##    print('smtp:'+str(confemail["smtp"]))
##except:
##    pass
##try:
##    #print('login:'+str(confemail["login"]))
##except:
##    pass
#print (str('sudo '+str(oscurdir)+'/need/hdom-cs/linux/hdom-cs'))
def bingo():
    print ('bingo')
    return False
def send_mail(email,mstr):
    global conf,confemail
    strTo=email
# Define these once; use them twice!
    strFrom = str(confemail["from"].rstrip('\n'))

    # Create the root message and fill in the from, to, and subject headers
    msgRoot = MIMEMultipart('related')
    msgRoot['Subject'] = 'hdom alert'
    msgRoot['From'] = strFrom
    msgRoot['To'] = strTo
    msgRoot.preamble = 'This is a multi-part message in MIME format.'
    s = smtplib.SMTP_SSL(str(confemail["smtp"]))
    if str(confemail["from"].rstrip('\n'))=="noreply@follow-your-team-computers.com":
        s.login('noreply@follow-your-team-computers.com','5km6e7A583R')
    else:
        s.login(str(confemail["login"].rstrip('\n')),str(confemail["password"].rstrip('\n')))

    # Encapsulate the plain and HTML versions of the message body in an
    # 'alternative' part, so message agents can decide which they want to display.
    msgAlternative = MIMEMultipart('alternative')
    msgRoot.attach(msgAlternative)

    msgText = MIMEText("""
"""+str(mstr)+""" """)
    msgAlternative.attach(msgText)

    # We reference the image in the IMG SRC attribute by the ID we give it below
    msgText = MIMEText("""<table>
<tr><td>"""+str(mstr)+"""</td></tr>    
</table>""", 'html')
    msgAlternative.attach(msgText)

    # This example assumes the image is in the current directory
##    fp = open('unit.png', 'rb')
##    msgImage = MIMEImage(fp.read())
##    fp.close()
##
##    # Define the image's ID as referenced above
##    msgImage.add_header('Content-ID', '<image1>')
##    msgRoot.attach(msgImage)
    try:
        s.sendmail(strFrom, strTo, msgRoot.as_string())
        s.quit()
        print ('email envoye'+strTo)
        time.sleep(7)
    except:
        print ("erreur"+strTo)
class chk_output(Thread):
    def __init__(self):
        Thread.__init__(self)
    def run(self): 
        return subprocess.check_output([str(oscurdir)+'/need/hdom-cs/hdom-cs'] , shell = False) 
def anl_output():
    cmd=str(oscurdir)+'/need/hdom-cs/hdom-cs'
    #print (str(conf["dir",0]))
    with subprocess.Popen(cmd, bufsize=1000,universal_newlines=True,stdout=PIPE,stderr=PIPE,text=True,shell=True) as p:
        for line in p.stderr:
            #print('1:'+str(line)) # process line here
            for i in range(0,int(conf["nombre"])+1,1):
                #
##                try:
                if str(conf["dir",int(i)]) in str(line):
                    print (str(conf["dir",int(i)]))
                    tact=False
                    if str(conf["method",int(i)])=='access':
                        #print ('access enter')
                        z='accessed'
                        if 'Access' in str(line):
                            #print ('access ok')
                            tact=True
                    if str(conf["method",int(i)])=='modify':
                        print ('modify 1')
                        z='modified'
                        if 'Modify' in str(line):
                            print ('modify in')
                            tact=True
                    if str(conf["method",int(i)])=='rename':
                        z='renamed'
                        #print ('rename in')
                        if 'Rename' or 'Close' in str(line):
                            #print ('rename ok')
                            tact=True
                    if str(conf["method",int(i)])=='erase':
                        z='erased'
                        #print ('erase in')
                        if 'Erase' or 'Delete' in str(line):
                            #print ('erase ok')
                            tact=True
                    if tact==True:
                        if str(conf["action",i])=='mailto':
                            send_mail(conf["arguments",i],i,z)
                        elif str(conf["action",i])=='cmd':
                            xpath=conf["dir",i]
                            arg1=conf["arguments",i].replace('$PATH',str(xpath))
                            timet=time.strftime("%m-%d-%Y-%H-%M-%S")
                            arg2=arg1.replace('$TIME',str(timet))
                            rand=random.randrange(1,1000000000)
                            arg3=arg2.replace('$RANDOM',str(rand))
                            subprocess.call([str(arg3)] , shell = True)
                        print (str(conf["dir",int(i)])+' '+str(z)+' by'+str(procs))
                    else:
                        continue
##                except:
##                    print ('pass1')
    if p.returncode != 0:
        raise CalledProcessError(p.returncode, p.args)
mstr=""
class anl_output_process(Thread):
    global file,allt,verbose,mlt,mailto,mstr
    def __init__(self):
        Thread.__init__(self)
    def run(self):
        global file,allt,verbose,mlt,mailto,action,mstr
##        try:
        for proc in psutil.process_iter():
##                try:
                # this returns the list of opened files by the current process
                #print (str(proc))
            if str(allt)=="-a":
                mstr=str(mstr)+str(proc)+'\t'
            flist = proc.open_files()
            if flist:
                #print (str(flist))
                if str(verbose)=="-v" and str(allt)=="-a":
                    print(str(proc.pid)+str(proc.name))
                if str(allt)=="-a":
                    mstr=str(mstr)+str(proc.pid)+' '+str(proc.name)+' has files opened \t'
                for nt in flist:
                    if str(verbose)=="-v" and str(allt)=="-a":
                        print("\t",nt.path)
                    if str(allt)=="-a":
                        mstr=str(mstr)+""+str(nt.path)
                    if file in nt.path:
                        if str(allt)!="-a" and str(verbose)=="-v":
                            print (str(nt.path)+' '+str(action)+' by'+str(proc.pid)+' '+str(proc.name))
                        if str(allt)=="-a":
                            mstr=str(nt.path)+' '+str(action)+' by'+str(proc.pid)+' '+str(proc.name)

                # This catches a race condition where a process ends
                # before we can examine its files    
##                except psutil.NoSuchProcess as err:
##                    print("****",err)
##                    mstr=str(mstr)+str(err)
##        finally:
        if str(mlt)=="-m" and str(mstr)!="":
            send_mail(mailto,mstr)
threads = []       
##line = chk_output()
##line.start()
anlp=anl_output_process()
anlp.start()
print("All threads are started")

# On attend que les 10 threads aient terminés.
                    
    #print (str(str(x)+':'+str(hdomaccess.check_output)))
    #x+=1
##for unam in unem:
##    dossier['path',x]=unam.getAttribute('PATH'##    dossier['nombre']=x
####    comm = 'sudo dd if=/dev/sda of=/dev/sdb'
####    cloning = subprocess.Popen(shlex.split(comm),stdout = PIPE,text = True)
####    while True:
####        print(cloning.stdout.read())
##    #watcher[x]=watch(dossier['path',x])
####    watch_this = os.path.abspath(dossier['path',x])
####    watch_manager.add_watch(watch_this, pyinotify.ALL_EVENTS)
####        comm = 'sudo dd if=/dev/sda of=/dev/sdb'
####cloning = subprocess.Popen(shlex.split(comm),stdout = PIPE,text = True)
####while True:
####    print(cloning.stdout.read())
##    x+=1
##event_notifier.loop()

