#To define a particular parameter, replace the 'parameterName' inside itsm.getParameter('parameterName') with that parameter's name
html_file_or_csv_file=itsm.getParameter('html_csv')#"html/csv"
logs=["CONTAINMENT","HIPS","FIREWALL"]
#-----------------------------------------------------------------------------------------------------------------
import os
import time
from subprocess import PIPE,Popen
import sqlite3
import socket
import datetime



#-------------------------------------------------------------------------------------------------------------------
date=datetime.date.today()
t1=os.popen("time").read()
t1=t1.splitlines()[0].split()[-1].split(".")[0]
file_name=str(socket.gethostname())+"_"+str(date)+"_"+str(t1)
name = str(socket.gethostname())
if os.path.exists(r"C:\Windows\Temp\comodo_logs"):
    pass
else:
    os.mkdir(r"C:\Windows\Temp\comodo_logs")

#-------------------------------------------------------------------------------------------------------------------
#cases : It matches queries for given logs  
cases={"CONTAINMENT":"""SELECT datetime(LogDate) as Date, Path as Application,
CASE 
	when status = 0 then 'Running'
	when status = 1 then 'Completed'
	when status = 2 then 'Failed'
END as status,
CASE
	when action = 0 then 'Run Restricted'
	when action = 1 then 'Run Virtually'
	when action = 2 then 'Blocked'
	when action = 3 then 'Ignored'
END as action,
CASE
	when rating = 0 then 'Unrecognized'
	when rating = 1 then 'Unrecognized'
	when rating = 2 then 'Trusted'
	when rating = 3 then 'Malicious'
END as rating,
CASE
	when Condition = 0 then 'User'
	when Condition = 1 then 'Containment Policy'
	when Condition = 2 then 'Virtual Desktop'
	when Condition = 3 then 'Containment Service'
	when Condition = 4 then 'Contained Process'
	when Condition = 5 then 'Virtual Desktop Shell'
END as Condition,
        ifnull(parentName,"") as ParentName,Parentpid,
        replace(hex(ParentSha1),0000000000000000000000000000000000000000,"") as ParentSha1,
        replace(replace(ParentTree,"<","&lt;"),">","&gt;") as ParentTree,
        ifnull(CommonInfoUserName,"") as UserName,
        ifnull(CommonInfoDomain,"") as DomainName,
        ifnull(CommonInfoUserSid,"") as UserID  FROM SbEvents """,
      "HIPS":"""select datetime(logdate) as Date,Parent as Application,
      CASE
	  when action =  0 then 'Run Restricted'
	  when action = 1 then 'Run Virtually'
      when action = 2 then 'Blocked'
      when action = 3 then 'Ignored' 
      END as Action,
	  Target,hex(commoninfosha1) as Hash,CommonInfoUserName as Username,
      CommonInfoDomain as DomainID,CommonInfoUserSid as UserID   from DfEvents""",
       "FIREWALL":"""Select datetime(LogDate) as Date, 
Path as Application, 
      CASE
	  when action =  0 then 'Run Restricted'
	  when action = 1 then 'Run Virtually'
      when action = 2 then 'Blocked'
      when action = 3 then 'Ignored' 
      END as Action, 
Direction, Protocol,replace(hex(SrcAddr),0000000000000000000000000000000000000000,"") as SourceIP, 
SrcPort as SourcePort, replace(hex(DstAddr),0000000000000000000000000000000000000000,"") as DestinationIp, 
DstPort as DestinationPort, 
ifnull(CommonInfoUserName,"") as UserName, 
ifnull(CommonInfoDomain,"") as DomainName, 
ifnull(CommonInfoUserSid,"") as UserSID from FwEvents


       """
      }
queries=[]
for i in logs:
    queries.append([i,cases.get(i)])
#print queries
#-------------------------------------------------------------------------------------------------------------------
def zipmaker():
    os.chdir("C:\\Windows\\Temp")
    cmd = 'tar.exe -a -c -f '+'"'+'C:\\Windows\\Temp\\'+name+'.zip'+'"'+' comodo_logs'
    os.popen(cmd)
#     shutil.make_archive("C:\Windows\Temp\comodo_logs","zip")
#     os.rename("C:\Windows\Temp\comodo_logs.zip","C:\Windows\Temp\%s.zip"%file_name)

def ecmd(command):
	obj = Popen(command, shell = True, stdout = PIPE, stderr = PIPE)
	out, err = obj.communicate()
	if err:
		print err
	else:
		fileToSend=temp
		msgbody="""
		Hi,
		
		The Report File has been attached
		"""
		print emailreport(subject,emailto,emailfrom,password,smtpserver,port,msgbody,fileToSend)
#Connecting sqlite3 server
if html_file_or_csv_file=="html":
    print("Creating HTML FILE logs")
    css_table_template_file="""
html {
  font-family: sans-serif;
}

table {
  border-collapse: collapse;
  border: 2px solid rgb(200,200,200);
  letter-spacing: 1px;
  font-size: 0.8rem;
}

td, th {
  border: 1px solid rgb(190,190,190);
  padding: 10px 20px;
}

th {
  background-color: rgb(235,235,235);
}

td {
  text-align: center;
}

tr:nth-child(even) td {
  background-color: rgb(250,250,250);
}

tr:nth-child(odd) td {
  background-color: rgb(245,245,245);
}

caption {
  padding: 10px;
}
"""
    with open(r"C:\Windows\Temp\comodo_logs\minimal-table.css","w") as  f:
        f.write(css_table_template_file)
    connect=sqlite3.connect(r"C:\ProgramData\Comodo\Firewall Pro\cislogs.sdb")
    print("Connection Established Successfully")
    sq_3=connect.cursor()
    data_dict=[]
    for i,j in queries:
        print(i+" Logs")
        data,cols=sq_3.execute(j),[k[0] for k in sq_3.description]
        head_list=["\t<th>%s</th>\n"%col for col in cols]
        headers="".join(head_list)
        big_list=[]
        for row in data:
            ls=[]
            trs1="<tr>\n"
            for r in row:
                tds="\t<td>"+str(r)+"</td>\n"
                ls.append(tds)
            trs2="</tr>\n"
            big_list.append(trs1+"".join(ls)+trs2)
        table_values="".join(big_list)
        table="""
         <table>
      <tr>
        %s

      </tr>
        %s
    </table> 
    """%(headers,table_values)
        #print table
        html_file="""
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>Table template</title>
        <link href="minimal-table.css" rel="stylesheet" type="text/css">
      </head>
      <body>

        <br>
        \t %s
      </body>
    </html>"""%table
        #print(html_file)
        with open(r"C:\Windows\Temp\comodo_logs\%s.html"%i,"w") as g:
            g.write(html_file)

    connect.close()
    print("Closed Connection")
elif html_file_or_csv_file=="csv":
    print("Creating CSV FILE logs")
    connect=sqlite3.connect(r"C:\ProgramData\Comodo\Firewall Pro\cislogs.sdb")
    print("Connection Established Successfully")
    sq_3=connect.cursor()
    data_dict=[]
    for i,j in queries:
        #print(i)
        data,cols=sq_3.execute(j),[k[0] for k in sq_3.description]
        with open("C:\Windows\Temp\comodo_logs\%s_table.csv"%i,"w") as f:
            #print(",".join(cols))
            f.write(",".join(cols))
            f.write("\n")
            for values in data:
                #print(values)
                #print(",".join(list(str(value) for value in values)))
                f.write(",".join(str(value) for value in values))
                f.write("\n") 
        print("CSV File created Successfully..{}--->C:\Windows\Temp\comodo_logs\{}_table.csv".format(i,i))
    connect.close()
    print("Closed Connection")

    
def download(url, file_path): ### Downloading
    try:
        import urllib2
        import os
        request = urllib2.Request(url, headers={'User-Agent' : "Magic Browser"})
        parsed = urllib2.urlopen(request)
        with open(file_path, 'wb') as f:
            while True:
                chunk=parsed.read(100*1000*1000)
                if chunk:
                    f.write(chunk)
                else:
                    break
        return file_path
    except:
        url_object=urllib2.urlopen(url)
        download_data=url_object.read()
        with open(file_path, "wb") as writer:
            writer.write(download_data)
        return file_path
    
def sftp_transfer(winscp_program_path, script_path, file_to_send):
    script_code=r"""open sftp://username:password@Hostname  -hostkey=*  #Provide the credentials to connect sftp
cd c1report/reports    #Location where the zip file should be saved
put "%s"
close
exit
"""%file_to_send
    with open(script_path, "w") as writer:
        writer.write(script_code)
    os.chdir("C:\Windows\Temp")
    print(os.getcwd())
    transfer_object=Popen('%s /script="%s"'%("WinSCP_C1_SFTP.exe", script_path), shell=True, stdout=PIPE, stderr=PIPE)
    transfer_object.communicate()
    os.chdir("C:\Windows\Temp")
    return transfer_object.returncode   
zipmaker()
winscp_file_path=os.path.join("C:\Windows\Temp", 'WinSCP_C1_SFTP.exe')
print winscp_file_path
winscp_url="https://cdn-patchportal-one.comodo.com/portal/packages/spm/DYMO%20Label%20Software/x86/WinSCP.exe"
winscp_program_path=download(winscp_url, winscp_file_path)
winscp_script_file=os.path.join("C:\Windows\Temp", 'script_winscp.txt')
print winscp_script_file
res=sftp_transfer(winscp_program_path, winscp_script_file,r"C:\Windows\Temp\%s.zip"%name )
if res==0:
    print 'File Name: %s '%name
    print 'Transfering CCS LOGS %s Done'%('.'*15)
else:
    print res
    print 'Failed to Transfer CCS LOGS'