#!/bin/python3

import gi
gi.require_version("Gtk", "3.0")

import subprocess
import os
import sys
from datetime import datetime
from datetime import timedelta
import time
import glob
import signal
from gi.repository import Gtk, Gdk, GLib, GdkPixbuf
from subprocess import Popen, PIPE

CONFIG={}
CONFIG['logo']="/opt/XLinux/XLinux-Security/ondemand-scan.svg"
CONFIG['scanning']="/opt/XLinux/XLinux-Security/ondemand-scan-running.gif"
CONFIG['img_ok']="/opt/XLinux/XLinux-Security/security-high.png"
CONFIG['img_virus']="/opt/XLinux/XLinux-Security/security-low.png"

def cmdexec(cmd1="",cmd2=""):
  cmd=cmd1
  if cmd2!="": cmd=cmd2
  cmd=cmd.strip()
  if cmd.endswith('&'):
    cmd=cmd[:-1]
    subprocess.Popen(cmd,shell=True)
    return
  else:
    a=subprocess.getoutput(cmd)
    return a


class AVWINDOW(Gtk.Window):
  def __init__(self):
    global SERVICEPAKET_ENABLED,ROOTDIR,FILELIST,ICONS,VIRUSLOG,CONFIG
    pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(filename=CONFIG['logo'],width=40, height=40, preserve_aspect_ratio=True)
    super().__init__(title="XLinux Virenscanner",icon=pixbuf)
    grid = Gtk.Grid(margin=10,column_spacing=10,row_spacing=10,hexpand=True,column_homogeneous=False,row_homogeneous=False)
    
    pixbufanim = GdkPixbuf.PixbufAnimation.new_from_file(CONFIG['scanning'])
    self.status_image = Gtk.Image()
    self.status_image.set_from_animation(pixbufanim)
    self.status_image.show()
    grid.attach(self.status_image, 0, 0, 1, 2)
    
    grid.attach(Gtk.Label(label="<b>Aktuelle Datei:</b>",xalign=0,justify=0,use_markup=True,yalign=0), 1, 0, 1, 1)
    grid.attach(Gtk.Label(label="<b>Status:</b>",xalign=0,justify=0,use_markup=True,yalign=0), 1, 1, 1, 1)
    grid.attach(Gtk.Label(label="<b>Fortschritt:</b>",xalign=0,justify=0,use_markup=True,yalign=0), 1, 2, 1, 1)
    
    self.button = Gtk.Button(label="Scan abbrechen")
    self.button.connect("clicked", self.appclose)        
    grid.attach(self.button,3,0,1,2)

    
    self.aktuelle_datei=Gtk.Label(label="-",xalign=0,justify=0,use_markup=True,yalign=0,hexpand=True,width_chars=40,ellipsize=1); grid.attach(self.aktuelle_datei, 2, 0, 1, 1)
    self.anzahl_verdachtsfaelle=Gtk.Label(label="Liste Dateien auf",xalign=0,justify=0,use_markup=True,yalign=0); grid.attach(self.anzahl_verdachtsfaelle, 2, 1, 1, 1)
    self.gesamtanzahl=Gtk.Label(label="0 / 0",xalign=0,justify=0,use_markup=True,yalign=0); grid.attach(self.gesamtanzahl, 2, 2, 1, 1)
    
    LOGVIEW=Gtk.TreeView(expand=True)    
    LOGVIEW.set_model(VIRUSLOG)
    renderer_datum = Gtk.CellRendererText(ellipsize=False,wrap_mode=2,wrap_width=600,single_paragraph_mode=False)
    column_datum = Gtk.TreeViewColumn("Dateien mit Virenverdacht", renderer_datum, text=0)
    LOGVIEW.append_column(column_datum)
    scrolledwindow = Gtk.ScrolledWindow()
    scrolledwindow.set_hexpand(True)
    scrolledwindow.set_vexpand(True)
    scrolledwindow.set_min_content_height(100)
    scrolledwindow.set_min_content_width(600)
    scrolledwindow.set_size_request(600,100)
    self.set_size_request(600,100)
    scrolledwindow.add(LOGVIEW)
    grid.attach(scrolledwindow, 0, 3, 4, 1)

    self.add(grid);
    self.show_all();
    self.AV_filelist()
    #self.AV_do_scan();
    GLib.timeout_add(500, self.AV_do_scan)
    #GLib.timeout_add(100, self.AV_filelist)
    
  def AV_filelist(self):
    global ROOTDIR,FILELIST,RUNNING,GESAMTANZAHL
    FILELIST=[]
    GESAMTANZAHL=0
    fl=cmdexec("find " + ROOTDIR + " -xdev -type f ").strip().split("\n")
    for f in fl:
      GESAMTANZAHL=GESAMTANZAHL+1
      f=f.strip();
      FILELIST.append(f)
      self.gesamtanzahl.set_label("0 / "+str(GESAMTANZAHL))
      gtkrepaint()

  def AV_do_scan(self):
    global FILELIST,RUNNING,VIRENGEFUNDEN,GESCANNT,ROOTDIR,VIRUSLOG,CONFIG
    GESCANNT=0
    self.anzahl_verdachtsfaelle.set_label("Scan läuft, bitte warten ...")
    while len(FILELIST)>0 and RUNNING==1:
      f=FILELIST.pop(0)
      fkurz=f[len(ROOTDIR):]
      if (fkurz==""):
        fkurz=f
      self.aktuelle_datei.set_label(fkurz)
      gtkrepaint()
      r=cmdexec("clamdscan --multiscan --fdpass '"+f+"' >/dev/null 2>&1; echo $?").strip();
      if (r=="1"):
        VIRENGEFUNDEN=VIRENGEFUNDEN+1
        self.anzahl_verdachtsfaelle.set_label("Scan läuft, bisher "+str(VIRENGEFUNDEN)+" Verdachtsfälle.")
        VIRUSLOG.append([fkurz])
      GESCANNT=GESCANNT+1
      p=round(100/GESAMTANZAHL*GESCANNT,1)
      self.gesamtanzahl.set_label(str(GESCANNT)+" / "+str(GESAMTANZAHL)+"    "+str(p)+"%")
    if VIRENGEFUNDEN==0:
      self.status_image.set_from_file(CONFIG['img_ok']);
      self.anzahl_verdachtsfaelle.set_label("<span background='#a0ffa0'>Scan abgeschlossen, keine Viren gefunden.</span>")
    if VIRENGEFUNDEN>0:
      self.status_image.set_from_file(CONFIG['img_virus']);
      self.anzahl_verdachtsfaelle.set_label("<span background='#ffa0a0'>Scan abgeschlossen, Viren gefunden!</span>")
    self.button.set_label("Schließen")
    gtkrepaint()

  def appclose(*_):
    global RUNNING,FILELIST
    RUNNING=0
    Gtk.main_quit()
  
def gtkrepaint():
  while Gtk.events_pending(): Gtk.main_iteration_do(True)
  
  
# Service-Paket aktiv
ablaufdatum=cmdexec("xlinux-settings get SUPPORT_ENDDATE2")
x=datetime.now()
datum_heute=x.strftime("%Y%m%d")
SERVICEPAKET_ENABLED=0
if datum_heute<=ablaufdatum:
  SERVICEPAKET_ENABLED=1
else:
  SERVICEPAKET_ENABLED=0
  pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(filename="/home/mastro/Downloads/xlinux-av-scan.svg",width=40, height=40, preserve_aspect_ratio=True)
  dialog = Gtk.MessageDialog(flags=0,use_markup=True,message_type=Gtk.MessageType.INFO,buttons=Gtk.ButtonsType.OK,text="\n<b>Servicepaket abgelaufen</b>\n",title="XLinux Virenscanner",icon=pixbuf)
  dialog.format_secondary_markup("Der Virenscanner steht nicht zur Verfügung, weil für Ihren\nComputer kein gültiges Servicepaket registiert ist.\n\nBitte wenden Sie sich an <a href='https://www.mastro-it.de'>www.mastro-it.de</a> um das Servicepaket zu aktivieren.\n")
  dialog.run()
  dialog.destroy()
  sys.exit()

# Existiert clamdscan
if not os.path.isfile("/bin/clamdscan"):
  pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(filename="/home/mastro/Downloads/xlinux-av-scan.svg",width=40, height=40, preserve_aspect_ratio=True)
  dialog = Gtk.MessageDialog(flags=0,use_markup=True,message_type=Gtk.MessageType.INFO,buttons=Gtk.ButtonsType.OK,text="\n<b>Technisches Problem</b>\n",title="XLinux Virenscanner",icon=pixbuf)
  dialog.format_secondary_markup("Der Virenscanner steht nicht zur Verfügung, weil ein benötigtes\nProgramm auf dem Computer fehlt.\n\nBitte wenden Sie sich an <a href='https://www.mastro-it.de'>www.mastro-it.de</a> um das Problem zu lösen.\n")
  dialog.run()
  dialog.destroy()
  sys.exit()
  
#if len(sys.argv) == 1:
ROOTDIR=sys.argv[-1]
RUNNING=1
VIRENGEFUNDEN=0
VIRUSLOG = Gtk.ListStore(str)

win = AVWINDOW()
win.connect("delete-event", win.appclose)
win.connect("destroy", win.appclose)

win.show_all()
Gtk.main()
