#!/bin/python3

# Signaturenversion abfragen
# sigtool --info /var/lib/clamav/daily.cvd
# sigtool --info /var/lib/clamav/main.cvd
# sigtool --info /var/lib/clamav/bytecode.cvd

#!/usr/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, GLib, GdkPixbuf
from subprocess import Popen, PIPE

try:
    gi.require_version('AyatanaAppIndicator3', '0.1')
    from gi.repository import AyatanaAppIndicator3 as appindicator
except ValueError:
    gi.require_version('AppIndicator3', '0.1')
    from gi.repository import AppIndicator3 as appindicator


HOME=os.getenv("HOME")
FILE_FOUND=HOME+"/.cache/xlinux_virus_found"
VIRUS_FOUND_COUNT=0
VIRUS_FOUND_COUNT_NOT_IGNORED=0
FILE_FULLSCAN=HOME+"/.cache/xlinux_virus.fullscanfinished"
FILE_STATE="/tmp/xlinux-antivirus-fullscan"
FILE_STATE=HOME+"/.cache/xlinux_virus.listtoscan.state"
liststore = Gtk.ListStore(bool,str,str,str)
VIRENLISTE=Gtk.TreeView(expand=True)
FULLSCANINFO=Gtk.TreeView(expand=False)
FULLSCANDATE=Gtk.Label(expand=True,xalign=0)

ICONSTATE={}
FILEMTIME={}
CONF={}
ELEMENTS={}
ELEMENTS['BUTTON_START_SCAN'] = Gtk.Button(label="Jetzt scannen",xalign=0.5,hexpand=True,vexpand=True)
ICONS={
  'security-high':'/opt/XLinux/XLinux-Security/security-high.svg',
  'security-low':'/opt/XLinux/XLinux-Security/security-low.svg'
}
STATE={
  'firewall':0,
  'virenschutz':0,
  'virenschutz_found':0,
  'dns':0
}
VIRUS_FOUND_COUNT=0
APPICON_CURRENT=1

DNSSERVERLIST={
  "86.54.11.201":"DNSFILTER_M",
  "86.54.11.1":"DNSFILTER_M",
  "86.54.11.211":"DNSFILTER_MPA",
  "86.54.11.11":"DNSFILTER_MPA",
  "86.54.11.212":"DNSFILTER_MP",
  "86.54.11.12":"DNSFILTER_MP",
  "86.54.11.213":"DNSFILTER_MA",
  "86.54.11.13":"DNSFILTER_MA",
}




VIRENSCHUTZ_WHITELIST={}
FIREWALL_STATUS=0
FIREWALL_AKTIVIERT=0

class LogVirus(Gtk.Window):    
  def __init__(self):
    global HOME
    pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(filename=ICONS['security-high'],width=40, height=40, preserve_aspect_ratio=True)
    super().__init__(title="Scanlog des Virenscanner",icon=pixbuf)
    print("LogVirus: __init_")
    logstore = Gtk.ListStore(str,str,str)
    logs=glob.glob(HOME+'/.cache/xlinux_virus.scanlog.????????')
    if len(logs)>0:
      for lf in logs:
        with open(lf) as file:
          for line in file:
            x=line.strip().split('|')
            datum=x.pop(0)
            datei=x.pop(0)
            meldung=x.pop(0)
            logstore.append([datum,datei,meldung])
    LOGVIEW=Gtk.TreeView(expand=True)    
    LOGVIEW.set_model(logstore)
    renderer_datum = Gtk.CellRendererText(ellipsize=False,wrap_mode=2,wrap_width=600,single_paragraph_mode=False)
    column_datum = Gtk.TreeViewColumn("Datum", renderer_datum, text=0)
    LOGVIEW.append_column(column_datum)  
    renderer_filename = Gtk.CellRendererText(ellipsize=False,wrap_mode=2,wrap_width=600,single_paragraph_mode=False)
    column_filename = Gtk.TreeViewColumn("Dateiname", renderer_filename, text=1)
    renderer_meldung = Gtk.CellRendererText(ellipsize=False,wrap_mode=2,wrap_width=200,single_paragraph_mode=False)
    column_meldung = Gtk.TreeViewColumn("Uhrzeit", renderer_meldung, text=2)
    LOGVIEW.append_column(column_datum)
    LOGVIEW.append_column(column_filename)
    LOGVIEW.append_column(column_meldung)
    scrolledwindow = Gtk.ScrolledWindow()
    scrolledwindow.set_hexpand(True)
    scrolledwindow.set_vexpand(True)
    scrolledwindow.set_min_content_height(400)
    scrolledwindow.set_min_content_width(600)
    scrolledwindow.set_size_request(600,400)
    self.set_size_request(600,400)
    scrolledwindow.add(LOGVIEW)
    self.add(scrolledwindow)

class Virus_Found_Log(Gtk.Window):    
  def __init__(self):
    global HOME,ELEMENTS
    pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(filename=ICONS['security-low'],width=40, height=40, preserve_aspect_ratio=True)
    super().__init__(title="Virenfunde",icon=pixbuf)
    print("Virus_Found_Log: __init__")
    label1 = Gtk.Label(label="<b>Aktuell Viren-Verdachtsfälle:</b>",xalign=0,hexpand=True,use_markup=True)
    if "VIRUS_FOUND_LISTSTORE" not in ELEMENTS:
      #ELEMENTS['VIRUS_FOUND_LISTSTORE'] = Gtk.ListStore(bool,str,str,str)
      ELEMENTS['VIRUS_FOUND_LISTSTORE'] = Gtk.ListStore(bool,str)
    ELEMENTS['VIRUS_FOUND_LIST']=Gtk.TreeView(expand=True)
    renderer_toggle = Gtk.CellRendererToggle()
    renderer_toggle.connect("toggled", self.viren_liste_ignore_click)
    column_toggle = Gtk.TreeViewColumn("Ignorieren", renderer_toggle, active=0)
    ELEMENTS['VIRUS_FOUND_LIST'].append_column(column_toggle)
    #renderer_datum = Gtk.CellRendererText(ellipsize=False,wrap_mode=2,wrap_width=200,single_paragraph_mode=False)
    #column_datum = Gtk.TreeViewColumn("Datum", renderer_datum, text=1)
    #ELEMENTS['VIRUS_FOUND_LIST'].append_column(column_datum)  
    #renderer_uhrzeit = Gtk.CellRendererText(ellipsize=False,wrap_mode=2,wrap_width=200,single_paragraph_mode=False)
    #column_uhrzeit = Gtk.TreeViewColumn("Uhrzeit", renderer_uhrzeit, text=2)
    #ELEMENTS['VIRUS_FOUND_LIST'].append_column(column_uhrzeit)
    renderer_filename = Gtk.CellRendererText(ellipsize=False,wrap_mode=2,wrap_width=600,single_paragraph_mode=False)
    column_filename = Gtk.TreeViewColumn("Dateiname", renderer_filename, text=1)
    ELEMENTS['VIRUS_FOUND_LIST'].append_column(column_filename)
    ELEMENTS['VIRUS_FOUND_LIST'].set_model(ELEMENTS['VIRUS_FOUND_LISTSTORE'])
    scrolledwindow = Gtk.ScrolledWindow()
    scrolledwindow.set_hexpand(True)
    scrolledwindow.set_vexpand(True)
    scrolledwindow.set_min_content_height(200)
    scrolledwindow.set_min_content_height(400)
    scrolledwindow.set_min_content_width(600)
    scrolledwindow.set_size_request(600,400)
    self.set_size_request(600,400)
    scrolledwindow.add(ELEMENTS['VIRUS_FOUND_LIST'])
    
    grid = Gtk.Grid(margin=10,column_spacing=10,row_spacing=10,hexpand=True,column_homogeneous=True,row_homogeneous=False)
    grid.attach(label1,0,0,5,1)
    grid.attach(scrolledwindow,0,1,5,1)
    #button = Gtk.Button(label="Dateien löschen",xalign=0.5,hexpand=True)
    #button.connect("clicked", self.viren_click_delete_files)
    #grid.attach(button,0,1,1,1)
    #button = Gtk.Button(label="Schließen",xalign=0.5,hexpand=True)
    #button.connect("clicked", self.firewall_click_delete_trusted)
    #grid.attach(button,4,1,5,1)
    self.add(grid)
    #viren_update_liststore()
    self.show_all()

  def viren_liste_ignore_click(self, widget, path):
    global ELEMENTS,HOME
    ELEMENTS['VIRUS_FOUND_LISTSTORE'][path][0] = not ELEMENTS['VIRUS_FOUND_LISTSTORE'][path][0]
    if ELEMENTS['VIRUS_FOUND_LISTSTORE'][path][0]:
      cmdexec("echo '"+ELEMENTS['VIRUS_FOUND_LISTSTORE'][path][1]+"' >> '"+HOME+"/.cache/xlinux_virus_found_whitelist'")
    else:
      cmdexec("grep -v '^"+ELEMENTS['VIRUS_FOUND_LISTSTORE'][path][1]+"$' '"+HOME+"/.cache/xlinux_virus_found_whitelist' >/tmp/t 2>/dev/null ; cat /tmp/t > '"+HOME+"/.cache/xlinux_virus_found_whitelist' ")
    viren_update_viruslog()
    viren_update_scanlog()
    #self.show_all()

  def viren_click_delete_files(self,widget):
    global ELEMENTS,HOME
    print("viren_click_delete_files")
    for x in ELEMENTS['VIRUS_FOUND_LISTSTORE']:
      if x[0]==True:
        if len(x[3])>2:
          cmdexec("rm '"+HOME+"/"+x[3]+"' ")
    #viren_update_liststore()
    #self.show_all()
    return

  def viren_click_ignore_files(self,widget):
    global ELEMENTS,HOME
    print("viren_click_ignore_files")
    for x in ELEMENTS['VIRUS_FOUND_LISTSTORE']:
      if x[0]==True:
        if len(x[3])>2:
          cmdexec("echo '"+x[3]+"' >> '"+HOME+"/.cache/xlinux_virus_whitelist'")
    #viren_update_liststore()
    #self.show_all()
    return

class MyWindow(Gtk.Window):    
    def __init__(self):
        global SERVICEPAKET_ENABLED,ELEMENTS,ICONS
        pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(filename=ICONS['security-high'],width=40, height=40, preserve_aspect_ratio=True)
        super().__init__(title="XLinux Sicherheit",icon=pixbuf)
        ELEMENTS['notebook'] = Gtk.Notebook(hexpand=True)       
        infopage=self.infopage()
        virenfunde=self.viren_page()
        #firewall=self.firewall_page()
        firewall2=self.firewall_page2()
        dns=self.dnsfilter_page()
        ELEMENTS['notebook'].append_page(infopage, Gtk.Label(label="Übersicht"))
        ELEMENTS['notebook'].append_page(self.sicherheitsupdates_tab(), Gtk.Label(label="Sicherheitsupdates"))
        ELEMENTS['notebook'].append_page(virenfunde, Gtk.Label(label="Virenschutz"))
        #ELEMENTS['notebook'].append_page(firewall, Gtk.Label(label="Firewall"))        
        ELEMENTS['notebook'].append_page(firewall2, Gtk.Label(label="Firewall"))
        ELEMENTS['notebook'].append_page(dns, Gtk.Label(label="Malware-, Phishing-, Jugend-Filter"))        
        self.add(ELEMENTS['notebook'])
        
        
    def infopage_alarm_set(self,widget,value):
        global ELEMENTS
        cmdexec("xlinux-settings set XLINUXSECURITY_ALARM_VIRUS "+bool2str(ELEMENTS['INFO_ALARM_VIRUS'].get_active()))
        cmdexec("xlinux-settings set XLINUXSECURITY_ALARM_FIREWALL "+bool2str(ELEMENTS['INFO_ALARM_FIREWALL'].get_active()))
        cmdexec("xlinux-settings set XLINUXSECURITY_ALARM_DNS "+bool2str(ELEMENTS['INFO_ALARM_DNS'].get_active()))
        
    def infopage(self):
        print("infopage")
        #### Übersicht
        global VIRUS_FOUND_COUNT,FIREWALL_STATUS,ICONS,ELEMENTS,SYSTEMID,SERVICEPAKET_ENABLED
        hline=0
        vline=0
        grid1 = Gtk.Grid(margin=30,column_spacing=10,row_spacing=30,hexpand=True,column_homogeneous=True)
        grid2 = Gtk.Grid(margin=0,column_spacing=0,row_spacing=0,hexpand=True,vexpand=True,valign=3,row_homogeneous=True)
        sep=Gtk.Separator(orientation=0)
        
        ELEMENTS['servicepaket_abgelaufen'] = Gtk.Grid(margin=0,column_spacing=0,row_spacing=0,hexpand=False,vexpand=False,column_homogeneous=False,halign=3)
        label1 = Gtk.Label(label="",xalign=1,hexpand=False)
        label1.set_markup("<b>Sicherheitspaket gülitg bis:</b>")
        ELEMENTS['servicepaket_abgelaufen'].attach(label1, 0, 0, 1, 1)
        
        SYSTEMID=cmdexec("xlinux-systemid").strip()
        ablaufdatum=cmdexec("xlinux-settings get SUPPORT_ENDDATE2")
        ablaufdatum2=cmdexec("xlinux-settings get SUPPORT_ENDDATE")
        x=datetime.now()
        datum_heute=x.strftime("%Y%m%d")
        datum_in14tagen=(datetime.now() + timedelta(days=14) ).strftime('%Y%m%d')
        if ablaufdatum<datum_heute:
          ELEMENTS['ablaufdatum']=Gtk.Label(halign=0,hexpand=0)
          ELEMENTS['ablaufdatum'].set_markup(" Abgelaufen am "+ablaufdatum2+".  <a href=\"https://support.mastro-it.de/service?uuid="+SYSTEMID+"\">Verlängerung bestellen.</a>")
        else:
          if ablaufdatum<datum_in14tagen:
            ELEMENTS['ablaufdatum']=Gtk.Label(halign=0,hexpand=0)
            ELEMENTS['ablaufdatum'].set_markup(" "+ablaufdatum2+" <a href=\"https://support.mastro-it.de/service?uuid="+SYSTEMID+"\">Verlängerung bestellen.</a>")
          else:
            ELEMENTS['ablaufdatum'] = Gtk.Label(label=" "+ablaufdatum2 + ".",xalign=0,hexpand=False)
        ELEMENTS['servicepaket_abgelaufen'].attach(ELEMENTS['ablaufdatum'], 1, 0, 1, 1)
        
        grid1.attach(ELEMENTS['servicepaket_abgelaufen'], 0, hline, 3, 1)
        hline=hline+1
        
        if VIRUS_FOUND_COUNT==0:
          pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(filename=ICONS['security-high'],width=100, height=100, preserve_aspect_ratio=True)
        else:
          pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(filename=ICONS['security-low'],width=100, height=100, preserve_aspect_ratio=True)
        ELEMENTS['virenschutz_icon'] = Gtk.Image.new_from_pixbuf(pixbuf)
        ELEMENTS['virenschutz_icon'].set_halign(0.5)
        label1 = Gtk.Label(label="",xalign=0.5,hexpand=True)
        label1.set_markup("<b>Virenschutz</b>")
        grid1.attach(label1, vline, hline, 1, 1)
        grid1.attach(ELEMENTS['virenschutz_icon'], vline, hline+1, 1, 1)
        ELEMENTS['virenschutz_status'] = Gtk.Label(label="",xalign=0.5,hexpand=True)
        grid1.attach(ELEMENTS['virenschutz_status'], vline, hline+2, 1, 1)
        
        a=cmdexec("xlinux-settings get XLINUXSECURITY_ALARM_VIRUS || echo 1").strip()
        grid21 = Gtk.Grid(margin=00,column_spacing=10,row_spacing=00,column_homogeneous=False,halign=3)
        alarmieren = Gtk.Label(label="Alarmieren",xalign=0,hexpand=True)
        ELEMENTS['INFO_ALARM_VIRUS'] = Gtk.Switch(halign=Gtk.Align.START,active=str2bool(a))
        ELEMENTS['INFO_ALARM_VIRUS'].connect("state-set",self.infopage_alarm_set)
        ELEMENTS['INFO_ALARM_VIRUS'].set_tooltip_text("Statussymbol soll bei Alarm blinken.")
        grid21.attach(ELEMENTS['INFO_ALARM_VIRUS'],0,0,1,1)
        grid21.attach(alarmieren,1,0,1,1)
        grid1.attach(grid21,vline,hline+3,1,1)        
        
        vline=vline+1

        FIREWALL_STATUS=cmdexec("xlinux-settings get XLINUXSECURITY_FIREWALL_STATE || echo 0")
        if FIREWALL_STATUS=="1":
          pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(filename=ICONS['security-high'],width=100, height=100, preserve_aspect_ratio=True)
        else:
          pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(filename=ICONS['security-low'],width=100, height=100, preserve_aspect_ratio=True)
        ELEMENTS['firewall_icon'] = Gtk.Image.new_from_pixbuf(pixbuf)
        ELEMENTS['firewall_icon'].set_halign(0.5)
        label1 = Gtk.Label(label="",xalign=0.5,hexpand=True)
        label1.set_markup("<b>Firewall</b>")
        grid1.attach(label1, vline, hline, 1, 1)
        grid1.attach(ELEMENTS['firewall_icon'], vline, hline+1, 1, 1)
        ELEMENTS['firewall_status'] = Gtk.Label(label="",xalign=0.5,hexpand=True)
        grid1.attach(ELEMENTS['firewall_status'], vline, hline+2, 1, 1)
        

        a=cmdexec("xlinux-settings get XLINUXSECURITY_ALARM_FIREWALL || echo 1").strip()
        grid21 = Gtk.Grid(margin=00,column_spacing=10,row_spacing=00,column_homogeneous=False,halign=3)
        alarmieren = Gtk.Label(label="Alarmieren",xalign=0,hexpand=True)
        ELEMENTS['INFO_ALARM_FIREWALL'] = Gtk.Switch(halign=Gtk.Align.START,active=str2bool(a))
        ELEMENTS['INFO_ALARM_FIREWALL'].connect("state-set",self.infopage_alarm_set)
        ELEMENTS['INFO_ALARM_FIREWALL'].set_tooltip_text("Statussymbol soll bei Alarm blinken.")
        grid21.attach(ELEMENTS['INFO_ALARM_FIREWALL'],0,0,1,1)
        grid21.attach(alarmieren,1,0,1,1)
        grid1.attach(grid21,vline,hline+3,1,1)        

        vline=vline+1
        

        pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(filename=ICONS['security-low'],width=100, height=100, preserve_aspect_ratio=True)
        ELEMENTS['dns_icon'] = Gtk.Image.new_from_pixbuf(pixbuf)
        ELEMENTS['dns_icon'].set_halign(0.5)
        label1 = Gtk.Label(label="",xalign=0.5,hexpand=True)
        label1.set_markup("<b>Malware- und Phishingschutz</b>")
        grid1.attach(label1, vline, hline, 1, 1)
        grid1.attach(ELEMENTS['dns_icon'], vline, hline+1, 1, 1)
        ELEMENTS['dns_status'] = Gtk.Label(label="",xalign=0.5,hexpand=True)
        grid1.attach(ELEMENTS['dns_status'], vline, hline+2, 1, 1)

        a=cmdexec("xlinux-settings get XLINUXSECURITY_ALARM_DNS || echo 1").strip()
        grid21 = Gtk.Grid(margin=00,column_spacing=10,row_spacing=00,column_homogeneous=False,halign=3)
        alarmieren = Gtk.Label(label="Alarmieren",xalign=0,hexpand=True)
        ELEMENTS['INFO_ALARM_DNS'] = Gtk.Switch(halign=Gtk.Align.START,active=str2bool(a))
        ELEMENTS['INFO_ALARM_DNS'].connect("state-set",self.infopage_alarm_set)
        ELEMENTS['INFO_ALARM_DNS'].set_tooltip_text("Statussymbol soll bei Alarm blinken.")
        grid21.attach(ELEMENTS['INFO_ALARM_DNS'],0,0,1,1)
        grid21.attach(alarmieren,1,0,1,1)
        grid1.attach(grid21,vline,hline+3,1,1)                
        grid2.attach(grid1, 0, 0, 1, 1)
        return grid2
        
    def sicherheitsupdates_tab(self):
        global ELEMENTS
        hline=0
        grid1 = Gtk.Grid(margin=10,column_spacing=10,row_spacing=10,hexpand=True,column_homogeneous=False)
        label1 = Gtk.Label(label="Letzte Update-Suche:",xalign=0)
        ELEMENTS['updates_last_search'] = Gtk.Label(label="",xalign=0)
        BTN_APT_UPDATE = Gtk.Button(label="Updates jetzt suchen")
        BTN_APT_UPDATE.connect("clicked", cmdexec, "xlinux-update --search --force --allyes --showdesktopmessages &")        
        label2 = Gtk.Label(label="Letzte Update-Installation:",xalign=0)
        ELEMENTS['updates_last_install'] = Gtk.Label(label="",xalign=0)
        ELEMENTS['updates_btn_install'] = Gtk.Button(label="Updates installieren")
        ELEMENTS['updates_btn_install'].connect("clicked", cmdexec, "xlinux-update --install --force --allyes --showdesktopmessages &")        
        grid1.attach(label1, 0, hline, 1, 1)
        grid1.attach(ELEMENTS['updates_last_search'], 1, hline, 1, 1)
        grid1.attach(BTN_APT_UPDATE, 2, hline, 1, 1)
        hline=hline+1
        grid1.attach(label2, 0, hline, 1, 1)
        grid1.attach(ELEMENTS['updates_last_install'], 1, hline, 1, 1)
        grid1.attach(ELEMENTS['updates_btn_install'], 2, hline, 1, 1)

        ELEMENTS['UPDATELOG']=Gtk.TreeView(expand=True)
        renderer_infected = Gtk.CellRendererText(ellipsize=False,wrap_mode=2,single_paragraph_mode=False)
        column_infected = Gtk.TreeViewColumn("Erfolgreich installierte Updates", renderer_infected, text=0)
        ELEMENTS['UPDATELOG'].append_column(column_infected)  
        scrolledwindow = Gtk.ScrolledWindow()
        scrolledwindow.set_hexpand(True)
        scrolledwindow.set_vexpand(True)
        scrolledwindow.set_min_content_height(200)
        scrolledwindow.add(ELEMENTS['UPDATELOG'])
        hline=hline+1
        label1 = Gtk.Label(label="<b>Zuletzt installierte Sicherheitsupdates:</b>",xalign=0,hexpand=True,use_markup=True)
        grid1.attach(label1, 0, hline, 6, 1)
        hline=hline+1
        grid1.attach(scrolledwindow, 0, hline, 6, 6)
        self.sicherheitsupdates_update()
        return grid1

    def sicherheitsupdates_update(self):
        global ELEMENTS
        update_last_check=cmdexec("cat /var/cache/xlinux/last_update_check 2>/dev/null || echo unbekannt")
        update_last_install=cmdexec("cat /var/cache/xlinux/last_update_success 2>/dev/null || echo unbekannt")
        ELEMENTS['updates_last_search'].set_label(update_last_check)
        ELEMENTS['updates_last_install'].set_label(update_last_install)
        ELEMENTS['updates_btn_install'].set_sensitive(False)
        updates_avail=int(cmdexec("cat /var/cache/xlinux/last_update_check_updates_available 2>/dev/null  || echo 0"))
        if "UPDATELOG_LISTSTORE" not in ELEMENTS:
          ELEMENTS['UPDATELOG_LISTSTORE'] = Gtk.ListStore(str)
          ELEMENTS['UPDATELOG'].set_model(ELEMENTS['UPDATELOG_LISTSTORE'])
        ELEMENTS['UPDATELOG_LISTSTORE'].clear()
        if updates_avail>0:
          ELEMENTS['updates_btn_install'].set_sensitive(True)
          # /var/log/xlinux_update_log
          # /var/cache/xlinux/packages_upgradeable
        if os.path.isfile('/var/log/xlinux_update_log'):
          with open('/var/log/xlinux_update_log') as file:
            for line in file:
              ELEMENTS['UPDATELOG_LISTSTORE'].prepend([line.strip()])
        ELEMENTS['UPDATELOG'].show_all()

    def off_viren_liststore_select(self, widget, path):
        global liststore
        print("viren_liststore_select")
        liststore[path][0] = not liststore[path][0]
        #widget.set_active(not widget.get_active())
        
    def firewall_page(self):
        global FIREWALL_STATUS,ELEMENTS
        print("firewall_page")
        grid1=Gtk.Grid(margin=10,column_spacing=10,row_spacing=10,hexpand=True,column_homogeneous=False)
        
        erklaerung=Gtk.Label(label="",xalign=0,hexpand=False)
        erklaerung.set_markup("<b>Die Firewall blockiert alle eingehenden Verbindung zu diesem Computer.</b>\nDie aktivierte Firewall schützt Sie gegen Hacker die versuchen über das\nverbundene Netzwerk Zugriff auf Ihren Computer zu nehmen.")
        grid1.attach(erklaerung,0,0,10,1)
        
        if FIREWALL_STATUS=="1":
          e=True
        else:
          e=False
        #Firewall ein/aus
        grid2 = Gtk.Grid(margin=00,column_spacing=10,row_spacing=00,column_homogeneous=False)
        label1 = Gtk.Label(label="Firewall aktiviert (Hauptschalter)",xalign=0,hexpand=True)
        ELEMENTS['firewall_on'] = Gtk.Switch(halign=Gtk.Align.START,active=False)
        ELEMENTS['firewall_on'].connect("state-set",self.firewall_on_off)
        ELEMENTS['firewall_on'].set_tooltip_text("Schalten die Firewall ein oder aus.")
        grid2.attach(ELEMENTS['firewall_on'],0,0,1,1)
        grid2.attach(label1,1,0,1,1)
        grid1.attach(grid2,0,1,10,1)

        erklaerung=Gtk.Label(label="",xalign=0,hexpand=False)
        erklaerung.set_markup("\n<b>Vertrauenswürdige Netzwerke</b>\nWenn Sie von einem anderen Computer auf Drucker und Dateien zugreifen möchten,\ndie auf diesem Computer gespeichert sind, müssen Sie das aktuelle Netzwerk als\n'Vertrauenswürdig' einstufen oder die Firewall generell deaktivieren.\nIn öffentlichen Netzwerken (Hotspot's, Banhhöfe, Hotels) sollten Sie niemals\ndie Firewall deaktivieren oder diese als 'Vertrauenswürdig' einstufen!")
        grid1.attach(erklaerung,0,2,10,1)

        
        # Aktuell verbundenes Netzwerk
        grid2 = Gtk.Grid(margin=00,column_spacing=10,row_spacing=00,column_homogeneous=False)
        label1 = Gtk.Label(label="Das aktuelle Netzwerk ist vertrauenswürdig, Zugriff erlauben.",xalign=0.5,hexpand=False)
        ELEMENTS['firewall_trusted'] = Gtk.Switch(halign=Gtk.Align.START,active=False)
        ELEMENTS['firewall_trusted'].connect("state-set",self.firewall_change_trusted_current)
        grid2.attach(ELEMENTS['firewall_trusted'],0,0,1,1)
        grid2.attach(label1,1,0,1,1)
        grid1.attach(grid2,0,3,10,1)
        grid1.attach(Gtk.Label(label=" ",xalign=0.5,hexpand=False),0,4,10,1)
        
        button = Gtk.Button(label="Liste der vertrauenswürdigen Netzwerke löschen",xalign=0.5,hexpand=False)
        button.connect("clicked", self.firewall_click_delete_trusted)
        
        grid1.attach(button, 9, 5, 1, 1)
        #self.firewall_update_state()
        return grid1

    def firewall_page2(self):
        global FIREWALL_AKTIVIERT,ELEMENTS,CONF,SERVICEPAKET_ENABLED
        print("firewall_page")
        ELEMENTS['firewall_grid']=Gtk.Grid(margin=10,column_spacing=10,row_spacing=10,hexpand=True,column_homogeneous=True)
        
        erklaerung=Gtk.Label(label="",xalign=0,hexpand=False)
        erklaerung.set_markup("<b>Eine Firewall kontrolliert die alle Verbindungen zu diesem Computer.</b>\nWenn die Firewall aktiviert ist, werden eingehende Verbindungen zu diesem Computer blockiert.\nWenn ein Netzwerk von Ihnen als vertrauenswürdig markiert wird, dann lässt die Firewall Verbindungen\naus dem lokalen Netzwerk auf diesen Computer zu. Diese Freigabe ist zum Beispiel notwendig wenn Sie\nvon einem anderen Computern auf Dateien zugreifen möchten,\ndie auf diesem Computer gespeichert sind.")
        ELEMENTS['firewall_grid'].attach(erklaerung,0,0,5,1)
        
        
        
        if CONF['FIREWALL_AKTIVIERT']=="1":
          e=True
        else:
          e=False
        #Firewall ein/aus
        grid2 = Gtk.Grid(margin=00,column_spacing=10,row_spacing=00,column_homogeneous=False,halign=Gtk.Align.START)
        label1 = Gtk.Label(label="(Ein/Aus)",xalign=0,hexpand=True)
        ELEMENTS['firewall_on'] = Gtk.Switch(halign=Gtk.Align.START,active=e,sensitive=str2bool(SERVICEPAKET_ENABLED))
        ELEMENTS['firewall_on'].connect("state-set",self.firewall_on_off)
        ELEMENTS['firewall_on'].set_tooltip_text("Schalten die Firewall ein oder aus.")
        grid2.attach(ELEMENTS['firewall_on'],0,0,1,1)
        grid2.attach(label1,1,0,1,1)
        ELEMENTS['firewall_grid'].attach(Gtk.Label(use_markup=True,label='<b>Firewall verwenden:</b>',xalign=1,hexpand=False),0,1,1,1)
        ELEMENTS['firewall_grid'].attach(grid2,1,1,4,1)
        
        ELEMENTS['firewall_page_status']=Gtk.Label(label="",xalign=0,hexpand=True)
        ELEMENTS['firewall_grid'].attach(Gtk.Label(use_markup=True,label='<b>Status:</b>',xalign=1,hexpand=False),0,2,1,1)
        ELEMENTS['firewall_grid'].attach(ELEMENTS['firewall_page_status'],1,2,4,1)
        
        # Gespeicherte Netzwerke
        #erklaerung=Gtk.Label(label="",xalign=0,hexpand=False)
        #erklaerung.set_markup("<b>Gespeicherte Netzwerke</b>")
        #ELEMENTS['firewall_grid'].attach(erklaerung,0,2,10,1)
       
        
        # Aktuell verbundenes Netzwerk
        #grid2 = Gtk.Grid(margin=00,column_spacing=10,row_spacing=00,column_homogeneous=False)
        #label1 = Gtk.Label(label="Das aktuelle Netzwerk ist vertrauenswürdig, Zugriff erlauben.",xalign=0.5,hexpand=False)
        #ELEMENTS['firewall_trusted'] = Gtk.Switch(halign=Gtk.Align.START,active=False)
        #ELEMENTS['firewall_trusted'].connect("state-set",self.firewall_change_trusted_current)
        #grid2.attach(ELEMENTS['firewall_trusted'],0,0,1,1)
        #grid2.attach(label1,1,0,1,1)
        #grid1.attach(grid2,0,3,10,1)
        #grid1.attach(Gtk.Label(label=" ",xalign=0.5,hexpand=False),0,4,10,1)
        sw=Gtk.ScrolledWindow(hexpand=True)
        ELEMENTS['firewall_network_list']=Gtk.Grid(margin=5,column_spacing=5,row_spacing=5,hexpand=True,column_homogeneous=False)
        sw.set_hexpand(True)
        sw.set_vexpand(True)
        sw.set_min_content_height(50)
        sw.set_max_content_height(250)
        sw.add(ELEMENTS['firewall_network_list'])
        ELEMENTS['firewall_grid'].attach(sw,0,3,5,1)
        
        #button = Gtk.Button(label="Liste der vertrauenswürdigen Netzwerke löschen",xalign=0.5,hexpand=False)
        #button.connect("clicked", self.firewall_click_delete_trusted)
        #ELEMENTS['firewall_grid'].attach(button, 9, 5, 1, 1)
        
        self.firewall_network_list_update()
        #self.firewall_update_state()
        return ELEMENTS['firewall_grid']

    def firewall_network_list_update(self):
        print("firewall_network_list_update")
        global firewall_network_list,ELEMENTS,STATE
        while True:
          if ELEMENTS['firewall_network_list'].get_child_at(0,0)!= None:
            ELEMENTS['firewall_network_list'].remove_row(0)
          else:
            break
        #firewall_network_list = Gtk.ListStore(str,str,bool)        
        ELEMENTS['firewall_network_list'].attach(Gtk.Label(use_markup=True,label='<b>Netzwerk</b>',xalign=0,hexpand=True),0,0,1,1)
        ELEMENTS['firewall_network_list'].attach(Gtk.Label(use_markup=True,label='<b>Letzte Nutzung</b>',xalign=0,hexpand=True),1,0,1,1)
        ELEMENTS['firewall_network_list'].attach(Gtk.Label(use_markup=True,label='<b>Netzwerk vertrauen</b>',xalign=0,hexpand=True),2,0,1,1)
        ELEMENTS['firewall_network_list'].attach(Gtk.Label(use_markup=True,label='<b>Löschen</b>',xalign=0,hexpand=True),3,0,1,1)

        current_mac=cmdexec("xlinux-settings get XLINUXSECURITY_FIREWALL_CURRENT || echo 1").strip()
        if os.path.isfile("/etc/xlinux/firewall_known_macs"):
          with open("/etc/xlinux/firewall_known_macs") as file:
            i=0
            for line in file:
              x=line.strip().split(';')
              if len(x)>=3:
                i=i+1
                mac=x.pop(0)
                datum=x.pop(0)
                trust=x.pop(0)
                if trust=='1':
                  trust_text='Ja.'
                  trust_change='0'
                else:
                  trust_text='Nein.'
                  trust_change='1'
                btn1=Gtk.Button(label=trust_text,xalign=0);
                btn1.connect("clicked",cmdexec,"xlinux-security-firewall trust "+mac+" "+trust_change+" &")
                btn2=Gtk.Button(label="Löschen",xalign=0);
                btn2.connect("clicked",cmdexec,"xlinux-security-firewall trust "+mac+"  &")                  

                if mac==current_mac and STATE['firewall']!=0:
                  datum="aktuell verwendet"

                ELEMENTS['firewall_network_list'].attach(Gtk.Label(label=mac,xalign=0,hexpand=True),0,i,1,1)
                ELEMENTS['firewall_network_list'].attach(Gtk.Label(label=datum,xalign=0,hexpand=True),1,i,1,1)                  
                ELEMENTS['firewall_network_list'].attach(btn1,2,i,1,1)
                if i>1:
                  ELEMENTS['firewall_network_list'].attach(btn2,3,i,1,1)
        ELEMENTS['firewall_network_list'].show_all()

    def firewall_click_delete_trusted(self):
        print("firewall_click_delete_trusted")
        cmdexec("xlinux-settings set XLINUXSECURITY_FIREWALL_TRUSTED")
        cmdexec("xlinux-security-firewall")
        #self.firewall=self.firewall_page()
        self.firewall_update_state()

    def firewall_change_trusted_current(self,widget,value):
        print("firewall_change_trusted_current")
        MAC=cmdexec("xlinux-settings get XLINUXSECURITY_FIREWALL_CURRENT || echo 1").strip()
        TRUSTED_LIST=cmdexec("xlinux-settings get XLINUXSECURITY_FIREWALL_TRUSTED || echo ,").strip().replace(" ", "")
        if value==True:
          TRUSTED_LIST=TRUSTED_LIST+","+MAC+",".replace(",,", ",")
        else:
          TRUSTED_LIST=TRUSTED_LIST.replace(","+MAC+",", ",")
        TRUSTED_LIST=TRUSTED_LIST.replace(",,", ",")
        TRUSTED_LIST=TRUSTED_LIST.replace(",,", ",")
        cmdexec("xlinux-settings set XLINUXSECURITY_FIREWALL_TRUSTED '"+TRUSTED_LIST+"'")
        cmdexec("xlinux-security-firewall")
        #self.firewall=self.firewall_page()
        self.firewall_update_state()        

    def firewall_on_off(self, widget, value):
        global ELEMENTS
        print("firewall_on_off")
        e="0"
        if value==True:
          e="1"
        print("XLINUXSECURITY_FIREWALL="+str(e))
        cmdexec("xlinux-settings set XLINUXSECURITY_FIREWALL '"+e+"'")
        cmdexec("xlinux-security-firewall")
        #self.firewall=self.firewall_page()
        self.firewall_update_state()
        #ELEMENTS['servicepaket_abgelaufen'].set_visible(not ELEMENTS['servicepaket_abgelaufen'].get_visible())        
        
    def firewall_update_state(self):
        global ELEMENTS,ICONS,STATE,FIREWALL_AKTIVIERT,CONF
        print("firewall_update_state")
        S=cmdexec("xlinux-settings get XLINUXSECURITY_FIREWALL_STATE || echo 0").strip()
        #FIREWALL_AKTIVIERT=cmdexec("xlinux-settings get XLINUXSECURITY_FIREWALL || echo 1").strip()

        ELEMENTS['firewall_page_status'].set_markup("Unbekannt")
        ELEMENTS['firewall_status'].set_markup("<b>Unbekannt</b>")
        I=ICONS['security-low']
        STATE['firewall']=0

        if S=="0":
          ELEMENTS['firewall_page_status'].set_markup("Inaktiv.")
          ELEMENTS['firewall_status'].set_markup("<b>Inaktiv</b>")
        if S=="1":
          I=ICONS['security-high']
          STATE['firewall']=1
          ELEMENTS['firewall_page_status'].set_markup("Aktiviert. Alles wird geblockt.")
          ELEMENTS['firewall_status'].set_markup("<b>Aktiviert</b>")
        if S=="2":
          I=ICONS['security-high']
          STATE['firewall']=1
          ELEMENTS['firewall_page_status'].set_markup("Aktiviert. Nur der Zugriff aus dem lokalen Netzwerk wird zugelassen.")
          ELEMENTS['firewall_status'].set_markup("<b>Aktiviert</b>")
        
        #if CONF['FIREWALL_AKTIVIERT']=="1":
        #  ELEMENTS['firewall_on'].set_active(True)
        #else:
        #  ELEMENTS['firewall_on'].set_active(False)

        #if STATE['firewall']==1:
        #  MAC=cmdexec("xlinux-settings get XLINUXSECURITY_FIREWALL_CURRENT || echo 1").strip()
        #  TRUSTED_LIST=cmdexec("xlinux-settings get XLINUXSECURITY_FIREWALL_TRUSTED || echo ,").strip().replace(" ", "")
        #  if ","+MAC+"," in ","+TRUSTED_LIST+",":
        #    ELEMENTS['firewall_trusted'].set_active(True)
        #    ELEMENTS['firewall_status'].set_markup("<b>Vertrauenswürdiges\nNetzwerk</b>")
        #  else:
        #    ELEMENTS['firewall_trusted'].set_active(False)

        info_page_set_icon('firewall_icon',I)
        ELEMENTS['firewall_page_status'].show_all()
        ELEMENTS['firewall_grid'].show_all()
        ELEMENTS['firewall_status'].show_all()
        

    def dns_onoff(self, widget, value):
        global ELEMENTS
        e=0
        if value==True:
          e=1
        print("DNS-Filter-OnOff: "+str(e))
        cmdexec("xlinux-settings set XLINUXSECURITY_DNS_ENABLED '"+bool2str(value)+"'")
        ELEMENTS['DNSFILTER_OFF'].set_sensitive(value)
        ELEMENTS['DNSFILTER_M'].set_sensitive(value)
        ELEMENTS['DNSFILTER_MA'].set_sensitive(value)
        ELEMENTS['DNSFILTER_MP'].set_sensitive(value)
        ELEMENTS['DNSFILTER_MPA'].set_sensitive(value)
        
    def dnsfilter_page(self):
        global ELEMENTS
        print("gtknotebookpage_dnsfilter")
        sep=Gtk.Separator(orientation=0)
        grid1=Gtk.Grid(margin=10,column_spacing=10,row_spacing=10,hexpand=True,column_homogeneous=True)
        hline=0

        DNSSERVER_CURRENT=cmdexec("xlinux-settings get DNSSERVER").strip()

        label1=Gtk.Label(label="",xalign=0,hexpand=True)
        label1.set_markup("<b>DNS-Filter</b>\nWenn Sie eine Webseite aufrufen, muss der Webbrowser zuvor eine DNS-Anfrage an das Internet stellen,\num zu ermitteln unter welcher IP-Adresse die Webseite erreichbar ist. Der DNS-Filter prüft diese Anfragen\ngegen eine Block-Liste und gibt gegebenenfalls eine falsche Antwort zurück.\n\nWir haben keinen Einfluss auf die Block-Listen. Wenn Webseiten teilweise nicht korrekt funktionieren liegt\ndas in der Regel an dem Werbeblocker. Wählen Sie in diesem Fall nur den Phishingschutz und Jugendschutz aus.\n")
        grid1.attach(label1,0,hline,10,1)
        hline=hline+1


        #DNSSERVER_ONOFF=cmdexec("xlinux-settings get XLINUXSECURITY_DNS_ENABLED | echo 1").strip()
        #grid2 = Gtk.Grid(margin=00,column_spacing=10,row_spacing=00,column_homogeneous=False)
        #label1 = Gtk.Label(label="DNS-Filter verwenden.",xalign=0,hexpand=True)
        #ELEMENTS['DNS_ONOFF'] = Gtk.Switch(halign=Gtk.Align.START,active=DNSSERVER_ONOFF)
        #ELEMENTS['DNS_ONOFF'].connect("state-set",self.dns_onoff)
        #ELEMENTS['DNS_ONOFF'].set_tooltip_text("DNS-Filter verwenden.")
        #grid2.attach(ELEMENTS['DNS_ONOFF'],0,0,1,1)
        #grid2.attach(label1,1,0,1,1)
        #grid1.attach(grid2,1,hline,8,1)
        #hline=hline+1

        EN=True
        ELEMENTS['DNSFILTER_OFF'] = Gtk.RadioButton(label="Deaktiviert / eigene DNS-Konfiguration",sensitive=EN,active=True)
        ELEMENTS['DNSFILTER_M'] = Gtk.RadioButton(label="Malware/Phishing-Schutz", group=ELEMENTS['DNSFILTER_OFF'],sensitive=EN)
        ELEMENTS['DNSFILTER_MA'] = Gtk.RadioButton(label="Malware/Phishing-Schutz + Werbeblocker", group=ELEMENTS['DNSFILTER_OFF'],sensitive=EN)
        ELEMENTS['DNSFILTER_MP'] = Gtk.RadioButton(label="Malware/Phishing-Schutz + Jugendschutz", group=ELEMENTS['DNSFILTER_OFF'],sensitive=EN)
        ELEMENTS['DNSFILTER_MPA'] = Gtk.RadioButton(label="Malware/Phishing-Schutz + Werbeblocker + Jugendschutz", group=ELEMENTS['DNSFILTER_OFF'],sensitive=EN)
        
        DNSSERVER_CURRENT=cmdexec("xlinux-settings get XLINUXSECURITY_DNS_CURRENT || echo OFF").strip()
        ELEMENTS['DNSFILTER_'+DNSSERVER_CURRENT].set_active(True)

        ELEMENTS['DNSFILTER_OFF'].connect("toggled", self.dnsfilter_set_server, "DNSFILTER_OFF")
        ELEMENTS['DNSFILTER_M'].connect("toggled", self.dnsfilter_set_server, "DNSFILTER_M")
        ELEMENTS['DNSFILTER_MA'].connect("toggled", self.dnsfilter_set_server, "DNSFILTER_MA")
        ELEMENTS['DNSFILTER_MP'].connect("toggled", self.dnsfilter_set_server, "DNSFILTER_MP")
        ELEMENTS['DNSFILTER_MPA'].connect("toggled", self.dnsfilter_set_server, "DNSFILTER_MPA")
        grid1.attach(ELEMENTS['DNSFILTER_OFF'], 1, hline, 8, 1)
        hline=hline+1
        grid1.attach(ELEMENTS['DNSFILTER_M'], 1, hline, 8, 1)
        hline=hline+1
        grid1.attach(ELEMENTS['DNSFILTER_MA'], 1, hline, 8, 1)
        hline=hline+1
        grid1.attach(ELEMENTS['DNSFILTER_MP'], 1, hline, 8, 1)
        hline=hline+1
        grid1.attach(ELEMENTS['DNSFILTER_MPA'], 1, hline, 8, 1)
        hline=hline+1
        self.dnsfilter_read_state()
        return grid1      

    def dnsfilter_set_server(self, button, v1):
        global DNSSERVERLIST
        print("dnsfilter_set_server: "+v1)
        if button.get_active():
          v=v1.split("_")
          cmdexec("xlinux-settings set XLINUXSECURITY_DNS_SET "+v[1])
          cmdexec("xlinux-security-dns")
        return
        ip=""
        if button.get_active():
          for i in DNSSERVERLIST.keys():
            print("dnsfilter_set_server: i="+i+" , "+DNSSERVERLIST[i])
            if DNSSERVERLIST[i]==v1:
              ip=ip+" "+i
          cmdexec("xlinux-security-dns '"+ip.strip()+"'")
          print("DNS_SERVER="+ip.strip())
          #self.dnsfilter_read_state()
          
        

    def dnsfilter_read_state(self):
        global DNSSERVERLIST,ELEMENTS,STATE,ICONS
        DNSSERVER_CURRENT=cmdexec("xlinux-settings get XLINUXSECURITY_DNS_CURRENT || echo 'OFF'").strip()
        ELEMENTS['DNSFILTER_'+DNSSERVER_CURRENT].set_active(True)
        if DNSSERVER_CURRENT!="OFF":
          ic=ICONS['security-high']
          STATE['dns']=1
          ELEMENTS['dns_status'].set_markup("<b>Aktiviert</b>")
        else:
          ic=ICONS['security-low']
          STATE['dns']=0
          ELEMENTS['dns_status'].set_markup("<b>Inaktiv</b>")
        info_page_set_icon('dns_icon',ic)
        return
        dnslist=cmdexec("grep 'nameserver ' /etc/resolv.conf | awk '{print $2}'").strip().split("\n")
        current="DNSFILTER_OFF"
        ic=ICONS['security-low']
        STATE['dns']=0
        for i in dnslist:
          if current=="DNSFILTER_OFF":
            if i in DNSSERVERLIST:
              current=DNSSERVERLIST[i]
              STATE['dns']=1
              ic=ICONS['security-high']
        print("DNSFILTER Found: "+current)
        info_page_set_icon('dns_icon',ic)
        ELEMENTS[current].set_active(True)

    def virenschutz_on_off(self, widget, value):
        print("virenschutz_on_off")
        global CONF
        e="0"
        if value==True:
          e="1"
        CONF['VIRENSCHUTZ_AKTIVIERT']=e
        cmdexec("xlinux-settings set XLINUXSECURITY_VIRENSCHUTZ_AKTIVIERT '"+e+"'")
        if e=="0":
          cmdexec("xlinux-security-av-daemon --off")
        else:
          cmdexec("xlinux-security-av-daemon --ondemand &")
          
        
    def viren_page(self):
        print("viren_page")
        #### Notebook: Legende
        global liststore,VIRENLISTE,FULLSCANINFO,BUTTON_START_SCAN,FULLSCANDATE,ELEMENTS,CONF,SERVICEPAKET_ENABLED
        hline=0
        grid1 = Gtk.Grid(margin=10,column_spacing=10,row_spacing=10,hexpand=True,column_homogeneous=True)
        sep=Gtk.Separator(orientation=0)
        
                       
        # Virenschutz Ein/Aus
        grid2 = Gtk.Grid(margin=00,column_spacing=10,row_spacing=10,column_homogeneous=False,halign=Gtk.Align.START)
        ELEMENTS['virenschutz_on'] = Gtk.Switch(halign=Gtk.Align.START,active=str2bool(CONF['VIRENSCHUTZ_AKTIVIERT']),sensitive=str2bool(SERVICEPAKET_ENABLED))
        ELEMENTS['virenschutz_on'].connect("state-set",self.virenschutz_on_off)
        ELEMENTS['virenschutz_on'].set_tooltip_text("Virenschutz verwenden?")
        ELEMENTS['virenschutz_status_text']=Gtk.Label(label="",xalign=1,hexpand=False,use_markup=True)
        grid2.attach(ELEMENTS['virenschutz_on'],1,0,1,1)
        grid2.attach(Gtk.Label(label="<b>Virenschutz verwenden:</b>",xalign=1,hexpand=False,use_markup=True),0,0,1,1)
        grid2.attach(Gtk.Label(label="<b>Status:</b>",xalign=1,hexpand=False,use_markup=True),0,1,1,1)
        grid2.attach(ELEMENTS['virenschutz_status_text'],1,1,1,1)
        grid1.attach(grid2,0,0,3,1)

        # Signaturen
        ELEMENTS['viren_signaturen_zeit'] = Gtk.Label(label="",xalign=0,hexpand=True)
        ELEMENTS['viren_signaturen_count'] = Gtk.Label(label="",xalign=0,hexpand=True)
        frame_sig=Gtk.Frame(label="Signaturversion ",hexpand=True,vexpand=False)
        grid_sig= Gtk.Grid(margin=5,column_spacing=5,row_spacing=5,hexpand=True)
        label1 = Gtk.Label(label="Letzte Update:",xalign=1,hexpand=True)
        grid_sig.attach(label1, 0, 0, 1, 1)
        grid_sig.attach(ELEMENTS['viren_signaturen_zeit'], 1, 0, 1, 1)
        label1 = Gtk.Label(label="Signaturen:",xalign=1,hexpand=True)
        grid_sig.attach(label1, 0, 1, 1, 1)
        grid_sig.attach(ELEMENTS['viren_signaturen_count'], 1, 1, 1, 1)
        frame_sig.add(grid_sig)
        grid1.attach(frame_sig, 4, 0, 2, 1)


        # Full Virus Scan
        #frame_fullscan=Gtk.Frame(label="Komplettscan",hexpand=True,vexpand=False)
        #grid_full= Gtk.Grid(margin=5,column_spacing=5,row_spacing=5,hexpand=True)
        #label1 = Gtk.Label(label="Datum/Zeit:",xalign=1,hexpand=True)
        #grid_full.attach(label1,0,0,1,1)
        #grid_full.attach(FULLSCANDATE,1,0,1,1)
        #label1 = Gtk.Label(label="Verzeichnis:",xalign=1,hexpand=True)
        #grid_full.attach(label1,0,1,1,1)
        #label1 = Gtk.Label(label=HOME,xalign=0,hexpand=True)
        #grid_full.attach(label1,1,1,1,1)
        #grid_full.attach(ELEMENTS['BUTTON_START_SCAN'], 2, 0, 1, 2)
        #frame_fullscan.add(grid_full)
        #ELEMENTS['BUTTON_START_SCAN'].connect("clicked", self.viren_fullscan_starten)
        #grid1.attach(BUTTON_START_SCAN, 3, 4, 2, 1)
        #grid1.attach(frame_fullscan, 3, 0, 3, 1)

        # Scan-Logfile
        ELEMENTS['SCANLOG']=Gtk.TreeView(expand=True)
        renderer_infected = Gtk.CellRendererText(ellipsize=False,wrap_mode=2,wrap_width=200,single_paragraph_mode=False)
        column_infected = Gtk.TreeViewColumn("Status", renderer_infected, text=0)
        ELEMENTS['SCANLOG'].append_column(column_infected)  

        renderer_datum = Gtk.CellRendererText(ellipsize=False,wrap_mode=2,wrap_width=200,single_paragraph_mode=False)
        column_datum = Gtk.TreeViewColumn("Datum/Uhrzeit", renderer_datum, text=1)
        ELEMENTS['SCANLOG'].append_column(column_datum)  
     
        renderer_filename = Gtk.CellRendererText(ellipsize=False,wrap_mode=2,wrap_width=600,single_paragraph_mode=False)
        column_filename = Gtk.TreeViewColumn("Dateiname", renderer_filename, text=2)
        ELEMENTS['SCANLOG'].append_column(column_filename)
        scrolledwindow = Gtk.ScrolledWindow()
        scrolledwindow.set_hexpand(True)
        scrolledwindow.set_vexpand(True)
        scrolledwindow.set_min_content_height(200)
        scrolledwindow.add(ELEMENTS['SCANLOG'])
        
        label1 = Gtk.Label(label="<b>Zuletzt geprüfte Dateien:</b>",xalign=0,hexpand=True,use_markup=True)
        grid1.attach(label1, 0, 6, 6, 1)
        grid1.attach(scrolledwindow, 0, 7, 6, 6)

        #label1 = Gtk.Label(label=":",xalign=1,hexpand=True)
        #label1.set_markup("<b>Ausgewählte:</b>")
        #grid1.attach(label1, 0, 13, 1, 1)

        #button = Gtk.Button(label="löschen",xalign=0.5,hexpand=False)
        #button.connect("clicked", self.viren_click_delete_files)
        #grid1.attach(button, 1, 13, 1, 1)

        #button = Gtk.Button(label="ausblenden",xalign=0.5,hexpand=False)
        #button.connect("clicked", self.viren_click_ignore_files)
        #grid1.attach(button, 2, 13, 1, 1)

        #button = Gtk.Button(label="Logfile",xalign=0.5)
        #button.connect("clicked", self.viren_logfile_show)
        #grid1.attach(button, 4, 13, 1, 1)

        ELEMENTS['VIRENPAGE_VIREN_FOUND_BUTTON'] = Gtk.Button(label="Viren",xalign=0.5,hexpand=False)
        ELEMENTS['VIRENPAGE_VIREN_FOUND_BUTTON'].connect("clicked", viren_open_virus_found_window)
        grid1.attach(ELEMENTS['VIRENPAGE_VIREN_FOUND_BUTTON'], 0, 13, 3, 1)
                
        button = Gtk.Button(label="Hinweise",xalign=0.5)
        button.connect("clicked", self.viren_hinweisfenster)
        grid1.attach(button, 5, 13, 1, 1)        
        return grid1

    def viren_hinweisfenster(self,widget):
      global HOME
      print("viren_hinweisfenster")
      dialog = Gtk.MessageDialog(transient_for=self,flags=0,message_type=Gtk.MessageType.INFO,buttons=Gtk.ButtonsType.OK,text="Hinweise zum Virenschutz",)
      dialog.format_secondary_text("Kein Virenscanner kann 100%ige Sicherheit gewährleisten!\n\nDer Virenscanner überwacht Ihr Benutzerverzeichnis '"+HOME+"'\nund prüft jede Datei nach dem Schreibzugriff auf eventuelle Viren. Wenn\nein Virus gefunden wird, wird automatisch das Sicherheitstool angezeigt.\nZusätzlich können Sie jederzeit alle Dateien aus Ihrem Benutzerverzeichnis\nprüfen lassen.\nDer Virenscanner löscht selbst keine Dateien, zeigt jedoch gefundene Viren\nan und Sie können selbst entscheiden wann Sie welche Datei löschen.\n\nDer Virenscanner ist auf Linux-Systeme spezialisiert erkennt aber\nauch die meisten Viren die Windows gefährden. Da es für Linux praktisch\nkeine Viren gibt, gilt Linux auch ohne Virenscanner als sicheres\nBetriebssystem. Dennoch gibt Ihnen unser Virenschutz mehr Sicherheit.")
      dialog.run()
      dialog.destroy()
      self.show();
      return

    def off_viren_logfile_show(self,widget):
      global HOME
      print("viren_logfile_show")
      log=LogVirus()
      log.connect("delete-event", log.destroy)
      log.connect("destroy", log.destroy)
      log.show_all()
      self.show()
      return
      
    def off_viren_fullscan_starten(self,widget):
      global HOME, ELEMENTS
      print("viren_fullscan_starten")
      ELEMENTS['BUTTON_START_SCAN'].set_sensitive(False)
      #self.button1.set_sensitive(False);
      #self.button2.set_sensitive(False);
      cmdexec("xlinux-security-av-daemon --fullscan &")
      #dialog = Gtk.MessageDialog(transient_for=self,flags=0,message_type=Gtk.MessageType.INFO,buttons=Gtk.ButtonsType.OK,text="Virenscan gestartet",)
      #dialog.format_secondary_text("Der vollständige Virenscan des Benutzerverzeichnisses wurde gestartet.\n"+HOME+"\n\nSie können das Programm während des Virenscans schließen.\n\nBitte schalten Sie den Computer nicht ab. Sobald der Virenscan\nabgeschlossen wurde, erhalten Sie eine Benachrichtigung.\nFalls Viren gefunden wurden, öffnet sich das Programm automatisch.")
      #dialog.run()
      #dialog.destroy()
      self.show();
      return

    def off_viren_click_delete_files(self,widget):
      global liststore
      print("viren_click_delete_files")
      for x in liststore:
        print(x[3])
        if x[0]==True:
          if len(x[3])>2:
            cmdexec("rm '"+HOME+"/"+x[3]+"' &")
      #self.viren_update_list()
      return
    
    def off_viren_click_ignore_files(self,widget):
      global liststore,HOME
      print("viren_click_ignore_files")
      for x in liststore:
        print(x[3])
        if x[0]==True:
          if len(x[3])>2:
            cmdexec("echo '"+x[3]+"' >> '"+HOME+"/.cache/xlinux_virus_whitelist'")
      #self.viren_update_list()
      return

    def off_viren_update_list(self):
        global FILE_FOUND,liststore,VIRENLISTE,FULLSCANINFO,FILE_FULLSCAN,HOME,FULLSCANDATE,ICONS,STATE,VIRUS_FOUND_COUNT,FILEMTIME,ELEMENTS
        return
        print("viren_update_list")
        liststore = Gtk.ListStore(bool,str,str,str)
        text=""
        text_ignore=""
        whitelist={}
        if os.path.isfile(HOME+"/.cache/xlinux_virus_whitelist"):
          with open(HOME+"/.cache/xlinux_virus_whitelist") as file:
            for line in file:
              whitelist[line.strip()]=1
        if os.path.isfile(FILE_FOUND):
          print("UPDATE VIRENLISTE")
          with open(FILE_FOUND) as file:
            for line in file:
              x=line.split(' ')
              if len(x)>=3:
                datum=x.pop(0)
                uhrzeit=x.pop(0)
                fn=" ".join(x).strip()
                if os.path.isfile(HOME+"/"+fn):
                  # Datei existiert noch
                  if fn in whitelist:
                    text_ignore=text_ignore+fn+"\n"
                    text=text+datum+" "+uhrzeit+" "+fn+"\n"
                  else:
                    liststore.append([False,datum,uhrzeit,fn])
                    text=text+datum+" "+uhrzeit+" "+fn+"\n"
          with open(FILE_FOUND, "w") as text_file:
            text_file.write(text)
          if text_ignore!="":
            with open(HOME+"/.cache/xlinux_virus_whitelist", "w") as text_file:
              text_file.write(text_ignore)
        if len(liststore)>0 or STATE['virenschutz']!=1:
          info_page_set_icon('virenschutz_icon',ICONS['security-low'])
          STATE['virenschutz_found']=1
          if len(liststore)>VIRUS_FOUND_COUNT:
            print("VIRUS_FOUND_COUNT: "+str(VIRUS_FOUND_COUNT)+" > "+str(len(liststore)))
            self.show_all()
            ELEMENTS['notebook'].set_current_page(1)
        else:
          info_page_set_icon('virenschutz_icon',ICONS['security-high'])
          STATE['virenschutz_found']=0
        #self.set_icon(pixbuf)
        VIRUS_FOUND_COUNT=len(liststore)
        print("STATE_VIRENSCHUTZ "+str(STATE['virenschutz_found']))
        
        
        has_file_changed(FILE_FOUND)
        has_file_changed(HOME+"/.cache/xlinux_virus_whitelist")
        
        VIRENLISTE.set_model(liststore)
          
        list_fullscan = Gtk.ListStore(str,str)
        if os.path.isfile(FILE_FULLSCAN):
          with open(FILE_FULLSCAN) as file:
            l=file.readline().strip()
            if l!="":
              x=l.split('|')
              datum=x.pop(0)
              viren=x.pop(0).strip()
              FULLSCANDATE.set_label(datum)
              #list_fullscan.append([datum,viren])
        else:
          FULLSCANDATE="Noch nicht durchgeführt."
          #list_fullscan.append(["Unbekannt","?"])
        #FULLSCANINFO.set_model(list_fullscan)


    def off_viren_fullscan_state(self):
        global HOME,ELEMENTS,FILE_STATE
        print("load_scan_state")
        if os.path.isfile(FILE_STATE):
          with open(FILE_STATE) as file:
            l=file.readline().strip()
            x=l.split(' ')
            z=x.pop(0)
            t="Scan läuft:\n"+z;
            ELEMENTS['BUTTON_START_SCAN'].set_sensitive(False)
        else:
          t="Jetzt scannen"
          ELEMENTS['BUTTON_START_SCAN'].set_sensitive(True)
        ELEMENTS['BUTTON_START_SCAN'].set_label(t)
        
        #t="Jetzt scannen"
        #ELEMENTS['BUTTON_START_SCAN'].set_sensitive(True)
        #ELEMENTS['BUTTON_START_SCAN'].set_label(t)

        
       

def has_file_changed(f):
    global FILEMTIME
    if os.path.exists(f):
      a=os.path.getmtime(f)
    else:
      a=0
    if f in FILEMTIME.keys():
      b=FILEMTIME[f]
    else:
      b=0
    if a!=b:
      FILEMTIME[f]=a
      return True
    return False
  

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

def appicon_blinken():
  global indicator,APPICON_CURRENT,ELEMENTS,STATE,SERVICEPAKET_ENABLED,VIRUS_FOUND_COUNT,VIRUS_FOUND_COUNT_NOT_IGNORED
  i=ICONS['security-high']
  icon_old=APPICON_CURRENT;
  if STATE['firewall']==0 and ELEMENTS['INFO_ALARM_FIREWALL'].get_active():
    i=ICONS['security-low']
  if STATE['virenschutz']==0 and ELEMENTS['INFO_ALARM_VIRUS'].get_active():
    i=ICONS['security-low']
  if VIRUS_FOUND_COUNT_NOT_IGNORED>0 and ELEMENTS['INFO_ALARM_VIRUS'].get_active():
    i=ICONS['security-low']
  if STATE['virenschutz_found']==1 and ELEMENTS['INFO_ALARM_VIRUS'].get_active():
    i=ICONS['security-low']
  if STATE['dns']==0 and ELEMENTS['INFO_ALARM_DNS'].get_active():
    i=ICONS['security-low']
  if SERVICEPAKET_ENABLED!=1:
    i=ICONS['security-low']
    APPICON_CURRENT=1
  if APPICON_CURRENT==1 and i==ICONS['security-low']:
    APPICON_CURRENT=1-APPICON_CURRENT
  else:
    i=ICONS['security-high']
    APPICON_CURRENT=1
  if icon_old!=APPICON_CURRENT:
    indicator.set_icon_full(i,"XLinux Sicherheitscenter")
  GLib.timeout_add(500, appicon_blinken)

def info_page_set_icon(m,i):
  global ELEMENTS,ICONSTATE
  o=""
  if m in ICONSTATE:
    o=ICONSTATE[m]
  if o!=i:
    print("info_page_set_icon")
    pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(filename=i,width=100, height=100, preserve_aspect_ratio=True)
    ELEMENTS[m].set_from_pixbuf(pixbuf)
    ICONSTATE[m]=i

    
def virus_update_status():
  global CONF,ELEMENTS,ICONS,VIRUS_FOUND_COUNT
  # Virenschutz
  c=int(cmdexec("ps -ef | grep 'xlinux-security-av-daemon' | grep -v grep | wc -l"))
  t=""
  t2=""
  i=""
  if c>0:
    STATE['virenschutz']=1
    t="Aktiviert"
    i="security-high"
  else:
    STATE['virenschutz']=0
    t="Inaktiv"
    i="security-low"
  t2=t
  if VIRUS_FOUND_COUNT>0:
    t="Viren gefunden!"
    t3="Verdachtsfälle"
    i="security-low"
    if VIRUS_FOUND_COUNT==1:
      t3="Verdachtsfall"
    t2="<span background='#ff8888'> "+t2+", "+str(VIRUS_FOUND_COUNT)+" "+t3+" </span>"
  ELEMENTS['virenschutz_status'].set_markup("<b>"+t+"</b>")
  ELEMENTS['virenschutz_status_text'].set_label(t2)
  info_page_set_icon('virenschutz_icon',ICONS[i])
  
  
def viren_open_virus_found_window(*argv):
  log=Virus_Found_Log()
  log.connect("delete-event", log.destroy)
  log.connect("destroy", log.destroy)
  log.show_all()
  return

def viren_update_signatur_data():
  global ELEMENTS
  print("viren_update_signatur_data")
  SIG_TIME=""
  SIG_COUNT=0
  if os.path.isfile("/var/lib/clamav/daily.cvd"):
    SIG_TIME=cmdexec("sigtool --info /var/lib/clamav/daily.cvd 2>/dev/null | grep '^Build' | awk '{print $3 $4 $5}'").strip()
    S=cmdexec("sigtool --info /var/lib/clamav/daily.cvd 2>/dev/null | grep '^Signatures' | awk '{print $2}'")
    SIG_COUNT=SIG_COUNT+int(S)
  if os.path.isfile("/var/lib/clamav/daily.cld"):
    if SIG_TIME=="":
      SIG_TIME=cmdexec("sigtool --info /var/lib/clamav/daily.cld 2>/dev/null | grep '^Build' | awk '{print $3 $4 $5}'").strip()
    S=cmdexec("sigtool --info /var/lib/clamav/daily.cld 2>/dev/null | grep '^Signatures' | awk '{print $2}'")
    SIG_COUNT=SIG_COUNT+int(S)
  if os.path.isfile("/var/lib/clamav/main.cvd"):
    if SIG_TIME=="":
      SIG_TIME=cmdexec("sigtool --info /var/lib/clamav/main.cvd 2>/dev/null | grep '^Build' | awk '{print $3 $4 $5}'").strip()
    S=cmdexec("sigtool --info /var/lib/clamav/main.cvd 2>/dev/null | grep '^Signatures' | awk '{print $2}'")
    SIG_COUNT=SIG_COUNT+int(S)
  ELEMENTS['viren_signaturen_count'].set_label(str(SIG_COUNT))
  ELEMENTS['viren_signaturen_zeit'].set_label(SIG_TIME)
  return

def viren_update_scanlog():
  global ELEMENTS
  #ELEMENTS['SCANLOG']
  if "VIRUS_SCANLOG_LISTSTORE" not in ELEMENTS:
    ELEMENTS['VIRUS_SCANLOG_LISTSTORE'] = Gtk.ListStore(str,str,str)
  ELEMENTS['VIRUS_SCANLOG_LISTSTORE'].clear()
  if os.path.isfile('/tmp/xlinux_virus.scanlog.short'):
    log=cmdexec('tail -100 /tmp/xlinux_virus.scanlog.short').strip()
    loglines=log.split('\n')
    for line in loglines:
      x=line.split('|')
      if len(x)>2:
        status=x.pop(0)
        datum=x.pop(0)
        fn=" ".join(x).strip()
        ELEMENTS['VIRUS_SCANLOG_LISTSTORE'].prepend([status,datum,fn])
    #with open(HOME+'/.cache/xlinux_virus.scanlog.short') as file:
    #  for line in file:
    #    x=line.split('|')
    #    status=x.pop(0)
    #    datum=x.pop(0)
    #    fn=" ".join(x).strip()
    #    ELEMENTS['VIRUS_SCANLOG_LISTSTORE'].prepend([status,datum,fn])
  ELEMENTS['SCANLOG'].set_model(ELEMENTS['VIRUS_SCANLOG_LISTSTORE'])

def fullpath(f):
  global HOME
  f1=HOME+'/'+f
  if f.startswith("./"):
    f1=HOME+f[1:]
  if f.startswith("/"):  
    f1=f
  return f1

def viren_update_whitelist(*_):
  global HOME
  whitelist={}
  whitelist_change=0
  if os.path.isfile(HOME+"/.cache/xlinux_virus_found_whitelist"):
    with open(HOME+"/.cache/xlinux_virus_found_whitelist") as file:
      for line in file:
        l=line.strip()
        if l!="":
          if os.path.isfile(fullpath(l)):
            whitelist[l]=1
          else:
            whitelist_change=1
  if whitelist_change==1:
    with open(HOME+"/.cache/xlinux_virus_found_whitelist", 'w') as f:
      for line in whitelist:
        f.write("%s\n" % line)
  return whitelist

def viren_update_viruslog():
  global FILE_FOUND,VIRENLISTE,FULLSCANINFO,FILE_FULLSCAN,HOME,FULLSCANDATE,ICONS,STATE,VIRUS_FOUND_COUNT,FILEMTIME,ELEMENTS,VIRUS_FOUND_COUNT_NOT_IGNORED
  print("viren_update_liststore")
  #if not has_file_changed(FILE_FOUND) and not has_file_changed(FILE_FULLSCAN):
  #  return
  if "VIRUS_FOUND_LISTSTORE" not in ELEMENTS:
    #ELEMENTS['VIRUS_FOUND_LISTSTORE'] = Gtk.ListStore(bool,str,str,str)
    ELEMENTS['VIRUS_FOUND_LISTSTORE'] = Gtk.ListStore(bool,str)
  ELEMENTS['VIRUS_FOUND_LISTSTORE'].clear()
  text=""
  text_ignore=""
  vcount=0
  vcount_not_ignored=0
  whitelist=viren_update_whitelist()
  #whitelist_change=0
  #if os.path.isfile(HOME+"/.cache/xlinux_virus_found_whitelist"):
  #  with open(HOME+"/.cache/xlinux_virus_found_whitelist") as file:
  #    for line in file:
  #      l=line.strip()
  #      if l!="";
  #        if os.path.isfile(fullpath(l))
  #          whitelist[l]=1
  #        else
  #          whiteliste_change=1
  list_found={}
  if os.path.isfile(FILE_FOUND):
    with open(FILE_FOUND) as file:
      for line in file:
        print(line)
        x=line.split(' ')
        if len(x)>=3:
          datum=x.pop(0)
          uhrzeit=x.pop(0)
          fn=" ".join(x).strip()
          if os.path.isfile(HOME+"/"+fn):
            e=False
            # Datei existiert noch
            if fn in whitelist:
              e=True
              text_ignore=text_ignore+fn+"\n"
              text=text+datum+" "+uhrzeit+" "+fn+"\n"
            if fn not in list_found:
              #ELEMENTS['VIRUS_FOUND_LISTSTORE'].append([e,datum,uhrzeit,fn])
              ELEMENTS['VIRUS_FOUND_LISTSTORE'].append([e,fn])
              vcount=vcount+1
              if e==False:
                vcount_not_ignored=vcount_not_ignored+1
              list_found[fn]=1
            text=text+datum+" "+uhrzeit+" "+fn+"\n"
  #if vcount>0 or STATE['virenschutz']!=1:
  #  info_page_set_icon('virenschutz_icon',ICONS['security-low'])
  #  STATE['virenschutz_found']=1
  #  if vcount>VIRUS_FOUND_COUNT:
  #    print("VIRUS_FOUND_COUNT: "+str(VIRUS_FOUND_COUNT)+" > "+str(vcount))
  #    ELEMENTS['notebook'].show_all()
  #    ELEMENTS['notebook'].set_current_page(1)
  #else:
  #  info_page_set_icon('virenschutz_icon',ICONS['security-high'])
  #  STATE['virenschutz_found']=0
  #self.set_icon(pixbuf)
  print("STATE_VIRENSCHUTZ "+str(STATE['virenschutz_found']))
  if vcount==0:
    ELEMENTS['VIRENPAGE_VIREN_FOUND_BUTTON'].set_label("Aktuell keine Verdachtsfälle")
  else:
    if vcount==1:
      ELEMENTS['VIRENPAGE_VIREN_FOUND_BUTTON'].set_label("Virenverdachsfall anzeigen")
    else:
      ELEMENTS['VIRENPAGE_VIREN_FOUND_BUTTON'].set_label(str(vcount)+" Verdachtsfälle anzeigen")
  #if "VIRUS_FOUND_LIST" in ELEMENTS:
  #  ELEMENTS['VIRUS_FOUND_LIST'].show_all()
  #if "VIRENPAGE_VIREN_FOUND_BUTTON" in ELEMENTS:
  #  ELEMENTS['VIRENPAGE_VIREN_FOUND_BUTTON'].show_all()
  if VIRUS_FOUND_COUNT<vcount:
    win_show_page(1,2)
  VIRUS_FOUND_COUNT=vcount  
  VIRUS_FOUND_COUNT_NOT_IGNORED=vcount_not_ignored
  has_file_changed(FILE_FOUND)
#  has_file_changed(HOME+"/.cache/xlinux_virus_whitelist")
  
  #VIRENLISTE.set_model(ELEMENTS['VIRUS_FOUND_LISTSTORE'])


def win_show_page(s,i):
  global ELEMENTS,win
  ELEMENTS['notebook'].set_current_page(i)
  win.show()

def win_open(*_):  
  global win
  win.show()  

  
def win_hide(*_):  
  global win
  win.hide()
  return True


def app_build_menu():
  menu = Gtk.Menu()
  m1 = Gtk.MenuItem(label='Sicherheitscenter öffnen')
  m1.connect('activate', win_open)
  menu.append(m1)

  m1 = Gtk.MenuItem(label='Virenschutz')
  m1.connect('activate', win_show_page,2)
  menu.append(m1)

  m1 = Gtk.MenuItem(label='Firewall')
  m1.connect('activate', win_show_page,3)
  menu.append(m1)

  m1 = Gtk.MenuItem(label='Malware-/Phishingschutz')
  m1.connect('activate', win_show_page,4)
  menu.append(m1)

  #item_quit = Gtk.MenuItem(label='Sicherheitscenter beenden')
  #item_quit.connect('activate', beenden)
  #menu.append(item_quit)
  menu.show_all()
  return menu

def str2bool(v):
  return str(v).lower() in ("yes", "true", "t", "1")

def bool2str(v):
  if v:
    return "1"
  return "0"

def beenden(*a):
  cmdexec("xlinux-security-firewall off")
  cmdexec("xlinux-security-av-daemon --off")
  cmdexec("pkill -f 'xlinux-security-av-daemon' >/dev/null 2>&1")
  sys.exit(0)

def signal_handler(sig, frame):
    # Programm beenden wenn STRG+C
    print("STRG+C")
    beenden()
    sys.exit(0)

def signal_usr1(signum, stack):
    # Fenster anzeigen wenn Signal
    global win
    win.show()
    print("Received",signum)

def timer_300s():
  security_enabled()
  GLib.timeout_add(300*1000, timer_300s)

def security_enabled():
  global SERVICEPAKET_ENABLED,CONF,ELEMENTS
  s_alt=-1
  try: SERVICEPAKET_ENABLED
  except NameError: SERVICEPAKET_ENABLED=-1
  s_alt=SERVICEPAKET_ENABLED
  CONF['VIRENSCHUTZ_AKTIVIERT']=cmdexec("xlinux-settings get XLINUXSECURITY_VIRENSCHUTZ_AKTIVIERT || echo 1").strip()
  CONF['FIREWALL_AKTIVIERT']=cmdexec("xlinux-settings get XLINUXSECURITY_FIREWALL || echo 1").strip()
  ablaufdatum=cmdexec("xlinux-settings get SUPPORT_ENDDATE2")
  x=datetime.now()
  datum_heute=x.strftime("%Y%m%d")
  cmdexec("xlinux-security-dns >/dev/null 2>&1 ")
  SERVICEPAKET_ENABLED=0
  if datum_heute<=ablaufdatum:
    SERVICEPAKET_ENABLED=1
  else:
    SERVICEPAKET_ENABLED=0

  if s_alt!=SERVICEPAKET_ENABLED:
    if SERVICEPAKET_ENABLED==1:
      if str2bool(CONF['VIRENSCHUTZ_AKTIVIERT']):
        cmdexec("xlinux-security-av-daemon --ondemand >/dev/null 2>&1 &")
      if str2bool(CONF['FIREWALL_AKTIVIERT']):
        cmdexec("xlinux-security-firewall >/dev/null 2>&1 &")
      STATE['firewall']=1
      STATE['virenschutz']=1
      STATE['dns']=1

    else:
      cmdexec("xlinux-security-av-daemon --off >/dev/null 2>&1 ")
      cmdexec("xlinux-security-firewall off >/dev/null 2>&1 ")
      STATE['firewall']=0
      STATE['virenschutz']=0
      STATE['dns']=0

  #if 'servicepaket_abgelaufen' in ELEMENTS:
  #  ELEMENTS['servicepaket_abgelaufen'].set_visible(not str2bool(SERVICEPAKET_ENABLED))
  if 'virenschutz_on' in ELEMENTS.keys():
    ELEMENTS['virenschutz_on'].set_sensitive(str2bool(SERVICEPAKET_ENABLED))
  if 'firewall_on' in ELEMENTS.keys():
    ELEMENTS['firewall_on'].set_sensitive(str2bool(SERVICEPAKET_ENABLED))
  
  
    
def timer_1s():
  global HOME,FILE_FOUND,FILE_FULLSCAN,FILE_STATE,HOME,ELEMENTS,STATE
  # Viren-Gefunden-Liste
  if has_file_changed(FILE_FOUND) or has_file_changed(FILE_FULLSCAN):
    viren_update_viruslog()
  if has_file_changed('/tmp/xlinux_virus.scanlog.short'):
    viren_update_scanlog()
  virus_update_status()
  
  # Full-Scan-Status
  #if has_file_changed(FILE_STATE):
  #  win.viren_fullscan_state()

  # Signatur-Change
  if has_file_changed("/var/lib/clamav"):
    viren_update_signatur_data()

  # Firewall-Change
  if has_file_changed("/tmp/xlinux-security-firewall.state"):
    win.firewall_update_state()
  if has_file_changed("/etc/xlinux/firewall_known_macs"):
    win.firewall_network_list_update()
    
  # DNS-Change
  if has_file_changed("/etc/resolv.conf"):
    win.dnsfilter_read_state()
  
  if has_file_changed("/var/log/xlinux_update_log"):
    win.sicherheitsupdates_update()
  GLib.timeout_add(1000, timer_1s)
  return

    

signal.signal(signal.SIGUSR1, signal_usr1)
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)

def main():
  global OSVERSION,VIRUS_FOUND_COUNT,FILE_FOUND,SERVICEPAKET_ENABLED,STATE,ICONS,indicator,win,FIREWALL_AKTIVIERT,CONF
  # Alte PID Killen wenn Admin bereits läuft
  ownpid = os.getpid()
  fremdpid=cmdexec("ps -ef | grep 'xlinux-security-admin' | grep python | grep -v grep | awk '{print $2}' | grep -v '^"+str(ownpid)+"$'").strip()
  if fremdpid!="":
    print("kill -15 "+fremdpid)
    cmdexec("kill -15 "+fremdpid)
    #sys.exit(0)
  OSVERSION=int(cmdexec("cat /etc/debian_version | cut -d. -f1"))
  VIRUS_FOUND_COUNT=int(cmdexec("cat '"+FILE_FOUND+"' 2>/dev/null | wc -l "))
  timer_300s()
  
  # Statusicon
  indicator = appindicator.Indicator.new("XLinux Sicherheitscenter",ICONS['security-high'],appindicator.IndicatorCategory.APPLICATION_STATUS)
  indicator.set_status(appindicator.IndicatorStatus.ACTIVE)
  #indicator.set_menu(app_build_menu())
  indicator.set_menu(app_build_menu())
  security_enabled()
  win = MyWindow()
  win.show_all()
  win.hide()
  
  win.connect("delete-event", win_hide)
  win.connect("destroy", win_hide)
  GLib.timeout_add(1000, timer_1s)
  GLib.timeout_add(1500, appicon_blinken)
  if len(sys.argv) > 0:
    if "--icon" not in sys.argv:
      win.show()
      if "--viren" in sys.argv:
        ELEMENTS['notebook'].set_current_page(1)
      if "--firewall" in sys.argv:
        ELEMENTS['notebook'].set_current_page(2)
      if "--dns" in sys.argv:
        ELEMENTS['notebook'].set_current_page(3)

  Gtk.main()
  
def winopen(*_):
  global win
  win.destroy()
  win = MyWindow()
  win.show_all()
  win.hide()
  security_enabled()
  win.connect("delete-event", win_hide)
  win.connect("destroy", win_hide)
  #viren_update_liststore()
  
  #APPINDICATOR_ID = 'indicator_test'
  #indicator = appindicator.Indicator.new(APPINDICATOR_ID,"/opt/XLinux/XLinux-Security/security-high.svg",appindicator.IndicatorCategory.APPLICATION_STATUS,)
  #indicator.set_status(appindicator.IndicatorStatus.ACTIVE)
  #indicator.set_menu(build_menu())


main()