#!/bin/python3

#!/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
import datetime
import time
import glob
import signal
import re

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

class new_user(Gtk.Window):
  def __init__(self):
    super().__init__(title="Ersteinrichtung")
    label1=Gtk.Label(label="<b>Hauptbenutzer anlegen</b>",xalign=0.5,hexpand=True,use_markup=True)
    grid = Gtk.Grid(margin=10,column_spacing=10,row_spacing=10,hexpand=True,column_homogeneous=True,row_homogeneous=False)
    grid.attach(label1,0,0,4,1)
    label1=Gtk.Label(label="Anzeigename:",xalign=1,hexpand=True,use_markup=True)
    grid.attach(label1,0,1,2,1)
    self.anzeigename = Gtk.Entry()
    self.anzeigename.connect("key-release-event",self.update_systemname)
    grid.attach(self.anzeigename,2,1,2,1)
    label1=Gtk.Label(label="Systemlogin:",xalign=1,hexpand=True,use_markup=True)
    grid.attach(label1,0,2,2,1)
    self.systemname = Gtk.Entry(editable=False,can_focus=False)
    grid.attach(self.systemname,2,2,2,1)
    label1=Gtk.Label(label="Passwort:",xalign=1,hexpand=True,use_markup=True)
    grid.attach(label1,0,3,2,1)
    self.passwort = Gtk.Entry()    
    grid.attach(self.passwort,2,3,2,1)
    
    grid2 = Gtk.Grid(margin=00,column_spacing=10,row_spacing=00,column_homogeneous=False,halign=Gtk.Align.START)
    label1=Gtk.Label(label="Automatisch anmelden:",xalign=1,hexpand=True,use_markup=True)
    grid.attach(label1,0,4,2,1)
    self.sw_autologin = Gtk.Switch(halign=Gtk.Align.START,active=False,sensitive=True)
    grid.attach(self.sw_autologin,2,4,2,1)
    #self.sw_autologin.connect("state-set",self.firewall_on_off)
    #grid2.attach(self.sw_autologin,0,0,1,1)
    #grid2.attach(label1,1,0,1,1)
    
    self.btn1=Gtk.Button(label="Speichern & Reboot",xalign=0.5,hexpand=True)
    self.btn1.connect("clicked",self.check_input)
    self.btn1.connect("activate",self.check_input)
    grid.attach(self.btn1,0,5,2,1)

    self.btn2=Gtk.Button(label="Abbrechen",xalign=0.5,hexpand=True)
    self.btn2.connect("clicked",abbrechen)
    self.btn2.connect("activate",abbrechen)
    grid.attach(self.btn2,2,5,2,1)

    self.add(grid)
  
  def check_input(self,*a):
    geaendert=0
    gueltig=""
    alt=self.passwort.get_text()
    #a = re.sub(r"</?\[\d+>", "", a)
    print("Vor : "+alt)
    neu = re.sub(r"[^\d\w.-_#+*!$%&]", "", alt)
    print("Nach: "+neu)
    self.passwort.set_text(neu)
    if alt!=neu:
      geaendert=1
      gueltig=gueltig+"Das Passwort wurde angepasst.\n"
    if neu=="":
      gueltig=gueltig+"Das Passwort ist nicht zulässig.\n"
    if len(neu)<6:
      gueltig=gueltig+"Das Passwort muss mindestens 6 Zeichen haben.\n"

    alt=self.anzeigename.get_text().lower()
    #a = re.sub(r"</?\[\d+>", "", a)
    print("Vor : "+alt)
    neu=alt.replace('ä','ae')
    neu=neu.replace('ü','ue')
    neu=neu.replace('ö','oe')
    neu=neu.replace('ß','ss')
    neu=re.sub(r"[^\d\w]", "", neu)
    print("Nach: "+neu)
    self.systemname.set_text(neu)
    if alt!=neu:
      geaendert=1
      gueltig=gueltig+"Das Passwort wurde angepasst.\n"
    if neu=="":
      gueltig=gueltig+"Bitte geben Sie Ihren Anzeigename ein.\n"
    
    if gueltig!="":
      dialog = Gtk.MessageDialog(
          transient_for=self,
          flags=0,
          message_type=Gtk.MessageType.INFO,
          buttons=Gtk.ButtonsType.OK,
          text="Bitte prüfen Sie Ihre Eingaben",
      )
      dialog.format_secondary_text(gueltig)
      dialog.run()
      dialog.destroy()
      return
    else:
      t="useradd -m -s /bin/bash '"+self.systemname.get_text()+"'\n"
      t=t+"chfn --full-name '"+self.anzeigename.get_text()+"' '"+self.systemname.get_text()+"'\n"
      t=t+"echo -e \""+self.passwort.get_text()+"\n"+self.passwort.get_text()+"\n\" | (passwd '"+self.systemname.get_text()+"')\n"
      DEFAULT_GROUPS={"audio","bluetooth","cdrom","floppy","lpadmin","netdev","plugdev","scanner","systemd-journal users","video","sudo"}
      for a in DEFAULT_GROUPS:
        t=t+"usermod -a -G '"+a+"' '"+self.systemname.get_text()+"'\n"
      #t=t+"\n"
      #t=t+"usermod -G ${G},sudo '"+self.systemname.get_text()+"'\n"
      t=t+"rm /tmp/useradd \n"
      #t=t+"chmod +x /etc/xlinux-autostart/02_remove_init\n"
      t=t+"sync ; reboot \n"
      with open("/tmp/useradd", "a") as f:
        f.write(t)
      
      #cmdexec("useradd -m -s /bin/bash '"+self.systemname.get_text()+"' >>ersteinrichtung.log 2>&1")
      #cmdexec("chfn --full-name '"+self.anzeigename.get_text()+"' '"+self.systemname.get_text()+"' >>ersteinrichtung.log 2>&1")
      #cmdexec("echo -e \""+self.passwort.get_text()+"\n"+self.passwort.get_text()+"\n\" | (passwd '"+self.systemname.get_text()+"') >>ersteinrichtung.log 2>&1")
      #cmdexec("passwd '"+self.systemname.get_text()+"' < <(echo '"+self.passwort.get_text()+"';echo '"+self.passwort.get_text()+"') >>ersteinrichtung.log 2>&1")
      if self.sw_autologin.get_state():
        CONF="/usr/share/lightdm/lightdm.conf.d/98_autologin.conf"
        with open(CONF, "w") as f:
          f.write("[Seat:*]\n")
          f.write("autologin-user="+self.systemname.get_text()+"\n")
          f.write("autologin-user-timeout=0\n")
      CONF="/tmp/initxlinux_remove"
      with open(CONF, "w") as f:
        f.write("#!/bin/bash\n")
        f.write("userdel 'initxlinux'\n")
        f.write("rm -r '/home/initxlinux'\n")
        #f.write("rm -r '/etc/xlinux-autostart/02_initxlinux'\n")
      cmdexec("bash /tmp/useradd >ersteinrichtung.log 2>&1")
      beenden()
      


  def update_systemname(self,*a):
    alt=self.anzeigename.get_text().lower()
    #a = re.sub(r"</?\[\d+>", "", a)
    print("Vor : "+alt)
    neu=alt.replace('ä','ae')
    neu=neu.replace('ü','ue')
    neu=neu.replace('ö','oe')
    neu=neu.replace('ß','ss')
    neu=re.sub(r"[^\d\w]", "", neu)
    print("Nach: "+neu)
    self.systemname.set_text(neu)


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 str2bool(v):
  return str(v).lower() in ("yes", "true", "t", "1")

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

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

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

win = new_user()
win.set_position(Gtk.WindowPosition.CENTER)
win.show_all()
win.connect("delete-event", beenden)
win.connect("destroy", beenden)

if len(sys.argv) > 0:
  if "--icon" not in sys.argv:
    win.show()
  
Gtk.main()
sys.exit(0)


