#!/bin/python3

import gi, time
import subprocess
import os
import sys
import re

gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, GLib, GdkPixbuf, GObject, Pango
from subprocess import Popen, PIPE

sw_installed={}
sw_install_this={}
sw_uninstall_this={}
procstate=0
proc=subprocess

REALCURRENTUSER=subprocess.getoutput("whoami")
AUTOLOGINUSER=""
USERNAME=""
CURRENT_PW=""
dir_of_py_file = os.path.dirname(__file__)
ICON=dir_of_py_file+"/xlinux-user-pwchange.png"

if len(sys.argv)==2:
  if sys.argv[1]=="replace_autologin_script":
    if os.path.isfile("/tmp/xlinux-user-change-script.sh"):
      subprocess.getoutput("bash /tmp/xlinux-user-change-script.sh >/dev/null 2>&1 ; rm /tmp/xlinux-user-change-script.sh")
    sys.exit()
    


def get_current_data():
  global USERNAME, AUTOLOGINUSER,ANZEIGENAME
  if len(sys.argv)==2:
    USERNAME=sys.argv[1]
  else:
    USERNAME=subprocess.getoutput("whoami")
  AUTOLOGINUSER=subprocess.getoutput('cat /usr/share/lightdm/lightdm.conf.d/98_autologin.conf  2>&1 | grep "^autologin-user=" | cut -d= -f2')
  ANZEIGENAME=subprocess.getoutput("grep '^"+USERNAME+":' /etc/passwd | cut -d: -f5 | cut -d, -f1");


class AuthWindow(Gtk.Window):
  def __init__(self):
    global ICON
    super().__init__(title="Benutzeranmeldung")
    self.set_icon_from_file(ICON)
    grid = Gtk.Grid(margin=10,column_spacing=10,row_spacing=10)
    label1 = Gtk.Label(label="Login:",xalign=1)
    label1a = Gtk.Label(label=USERNAME,xalign=0)
    label2 = Gtk.Label(label="Bitte authentifizieren Sie sich mit Ihrem aktuellen Passwort,\num Zugriff auf die Passwort-Einstellungen zu erhalten.\n",xalign=2)
    label3 = Gtk.Label(label="Ihr aktuelles Passwort:",xalign=1)
    self.pw_old = Gtk.Entry(visibility=False,placeholder_text="")
    grid.attach(label2, 0, 0, 4, 1)
    grid.attach(label1, 0, 1, 2, 1)
    grid.attach(label1a, 2, 1, 2, 1)
    grid.attach(label3, 0, 2, 2, 1)
    grid.attach(self.pw_old, 2, 2, 2, 1)
    self.button1=Gtk.Button(label="Anmelden",sensitive=False)
    self.button1.connect("clicked", self.on_click_auth)
    self.pw_old.connect("activate",self.on_click_auth)
    self.pw_old.connect("changed",self.on_pw_entry)
    self.button2=Gtk.Button(label="Abbrechen")
    self.button2.connect("clicked", Gtk.main_quit)
    grid.attach(self.button1, 3, 3, 1, 1)
    grid.attach(self.button2, 0, 3, 1, 1)
    self.add(grid)
    
  def on_pw_entry(self,widget):
    self.button1.set_sensitive(False);
    if len(self.pw_old.get_text())>0:
      self.button1.set_sensitive(True);
    
  def on_click_auth(self,widget):
    global CURRENT_PW
    self.button1.set_sensitive(False);
    self.button2.set_sensitive(False);
    #while Gtk.events_pending():
    #  Gtk.main_iteration()
    pwo=self.pw_old.get_text()
    c=subprocess.getoutput("(echo  '"+pwo+"' ) | su - '"+USERNAME+"' >/dev/null 2>&1; echo $?")
    if c!="0":
      dialog = Gtk.MessageDialog(transient_for=self,flags=0,message_type=Gtk.MessageType.ERROR,buttons=Gtk.ButtonsType.OK,text="Abbruch",)
      dialog.format_secondary_text("Das eingegebene Passwort ist Falsch.\nBitte geben Sie ihr AKTUELLES Passwort von der Anmeldung ein.")
      dialog.run()
      dialog.destroy()
      self.button2.set_sensitive(True);
      self.show();
      return
    CURRENT_PW=pwo
    self.hide()
    win = MainWindow()
    win.connect("destroy", Gtk.main_quit)
    win.show_all()




class MainWindow(Gtk.Window):
  def __init__(self):
    global USERNAME,AUTOLOGINUSER,CURRENT_PW,ICON,ANZEIGENAME
    super().__init__(title="Benutzeranmeldung")
    self.set_icon_from_file(ICON)
    grid = Gtk.Grid(margin=10,column_spacing=10,row_spacing=10)
    label1 = Gtk.Label(label="Login:",xalign=1)
    label1a = Gtk.Label(label=USERNAME,xalign=0)
    label2 = Gtk.Label(label="Lassen Sie die Passwort-Felder leer, wenn\nSie das Passwort nicht ändern möchten.\nBitte nutzen Sie keine Sonderzeichen,\nnutzen Sie bitte nur A-Z und 0-9.",xalign=0.5)
    label3 = Gtk.Label(label="Neues Wunsch-Passwort:",xalign=1)
    label4 = Gtk.Label(label="Neues Passwort wiederholen:",xalign=1)
    label5 = Gtk.Label(label="automatische Anmeldung:",xalign=1)
    label6 = Gtk.Label(label="Anzeigename:",xalign=1)
    self.pw_new1 = Gtk.Entry(visibility=True,placeholder_text="Passwort nicht ändern")
    self.pw_new2 = Gtk.Entry(visibility=True,placeholder_text="Passwort nicht ändern")
    self.anzeigename = Gtk.Entry(visibility=True,placeholder_text="Sollte nicht leer sein!",text=ANZEIGENAME)
    self.autologin=Gtk.Switch(halign=Gtk.Align.START)
    if AUTOLOGINUSER==USERNAME:
      self.autologin.set_state(True)
    grid.attach(label1, 0, 0, 2, 1)
    grid.attach(label1a, 2, 0, 2, 1)
    grid.attach(label6, 0, 1, 2, 1)
    grid.attach(self.anzeigename, 2, 1, 2, 1)
    grid.attach(label5, 0, 2, 2, 1)
    grid.attach(self.autologin, 2, 2, 2, 1)
    grid.attach(label3, 0, 3, 2, 1)
    grid.attach(self.pw_new1, 2, 3, 2, 1)
    grid.attach(label4, 0, 4, 2, 1)
    grid.attach(self.pw_new2, 2, 4, 2, 1)
    grid.attach(label2, 0, 5, 4, 1)
    button=Gtk.Button(label="Speichern & Schließen")
    button.connect("clicked", self.on_saveclicked)
    grid.attach(button, 3, 6, 1, 1)
    self.add(grid)
  
  def on_saveclicked(self,widget):
    global USERNAME,AUTOLOGINUSER,CURRENT_PW,ICON,ANZEIGENAME
    # Update-Script löschen falls es existiert
    if os.path.isfile("/tmp/xlinux-user-change-script.sh"):
      subprocess.getoutput("rm /tmp/xlinux-user-change-script.sh >/dev/null 2>&1")
    # Anzeigename setzen
    #chfn --full-name "$U1" $U2
    s = re.sub(r'[^a-zA-Z0-9 äüöß]', '', self.anzeigename.get_text())
    if s!=self.anzeigename.get_text():
      self.anzeigename.set_text(s)
      dialog = Gtk.MessageDialog(transient_for=self,flags=0,message_type=Gtk.MessageType.ERROR,buttons=Gtk.ButtonsType.OK,text="Korrektur",)
      dialog.format_secondary_text("Der Anzeigename wurde von uns angepasst, bitte prüfen und nochmal speichern.")
      dialog.set_icon_from_file(ICON)
      dialog.run()
      dialog.destroy()
      return
    if s!=ANZEIGENAME:
      with open("/tmp/xlinux-user-change-script.sh", "a") as f:
        f.write('chfn --full-name "'+self.anzeigename.get_text()+'" "'+USERNAME+'"'+"\n")


    if self.pw_new1.get_text()!="":
      p1=self.pw_new1.get_text()
      s = re.sub(r'[^a-zA-Z0-9 äüöß]', '', p1)
      if p1!=s:
        dialog = Gtk.MessageDialog(transient_for=self,flags=0,message_type=Gtk.MessageType.ERROR,buttons=Gtk.ButtonsType.OK,text="Abbruch",)
        dialog.format_secondary_text("Aus Stabilitätsgründen sollte das Passwort nur Buchstaben und Ziffern bestehen. Keine Leerzeichen, Sonderzeichen und Umlaute.\n\nDa das Passwort nur lokal an dem Computer genutzt wird, ist ein komplexes Passwort auch nicht notwendig.")
        dialog.set_icon_from_file(ICON)
        dialog.run()
        dialog.destroy()
        return
      if p1!=self.pw_new2.get_text():
        dialog = Gtk.MessageDialog(transient_for=self,flags=0,message_type=Gtk.MessageType.ERROR,buttons=Gtk.ButtonsType.OK,text="Abbruch",)
        dialog.format_secondary_text("Bei der doppelten Eingabe des neuen Passworts, ist ein Tippfehler vorhanden.")
        dialog.set_icon_from_file(ICON)
        dialog.run()
        dialog.destroy()
        return
      if CURRENT_PW==self.pw_new1.get_text():
        dialog = Gtk.MessageDialog(transient_for=self,flags=0,message_type=Gtk.MessageType.ERROR,buttons=Gtk.ButtonsType.OK,text="Abbruch",)
        dialog.format_secondary_text("Das aktuelle und das neue Passwort dürfen nicht identisch sein.")
        dialog.set_icon_from_file(ICON)
        dialog.run()
        dialog.destroy()
        return
      if len(p1)<6:
        dialog = Gtk.MessageDialog(transient_for=self,flags=0,message_type=Gtk.MessageType.ERROR,buttons=Gtk.ButtonsType.OK,text="Abbruch",)
        dialog.format_secondary_text("Das neue Passwort muss mindestens 6 Zeichen haben.")
        dialog.set_icon_from_file(ICON)
        dialog.run()
        dialog.destroy()
        return
      # Passwd-Command
      if REALCURRENTUSER!="root":
        pc="(echo  '"+CURRENT_PW+"' ; echo '"+p1+"' ; echo '"+p1+"') | passwd '"+USERNAME+"' >/dev/null 2>&1 ; echo $?"
      else:
        pc="(echo '"+p1+"' ; echo '"+p1+"') | passwd '"+USERNAME+"' >/dev/null 2>&1 ; echo $?"
      c=subprocess.getoutput(pc)
      print("passwd-Returncode: "+c)
      if c!="0":
        dialog = Gtk.MessageDialog(transient_for=self,flags=0,message_type=Gtk.MessageType.ERROR,buttons=Gtk.ButtonsType.OK,text="Fehler",)
        dialog.format_secondary_text("Beim setzen des neuen Passworts ist ein Fehler auftreten, vermutlich ist das alte Passwort falsch.")
        dialog.set_icon_from_file(ICON)
        dialog.run()
        dialog.destroy()
        return
      else:
        CURRENT_PW=p1
        dialog = Gtk.MessageDialog(transient_for=self,flags=0,message_type=Gtk.MessageType.INFO,buttons=Gtk.ButtonsType.OK,text="Passwort wurde geändert",)
        dialog.set_icon_from_file(ICON)
        dialog.run()
        dialog.destroy()


  
    if ((self.autologin.get_state()==True) and (AUTOLOGINUSER!=USERNAME)):
      print("Autologin einschalten: "+str(self.autologin.get_state()));
      CONF="/usr/share/lightdm/lightdm.conf.d/98_autologin.conf"
      with open("/tmp/xlinux-user-change-script.sh", "a") as f:
        f.write("echo '[Seat:*]' > "+CONF+"\n")
        f.write("echo 'autologin-user="+USERNAME+"' >> "+CONF+"\n")
        f.write("echo 'autologin-user-timeout=0' >> "+CONF+"\n")
        f.write("echo  >> "+CONF+"\n")
      
    if ((AUTOLOGINUSER==USERNAME)or(REALCURRENTUSER=="root")) and (self.autologin.get_state()==False):
      print("Autologin abschalten: "+str(self.autologin.get_state()));
      with open("/tmp/xlinux-user-change-script.sh", "a") as f:
        f.write("rm -f /usr/share/lightdm/lightdm.conf.d/98_autologin.conf >/dev/null 2>&1\n")
        
    # Ausführen wenn Script-File existiert
    if os.path.isfile("/tmp/xlinux-user-change-script.sh"):
      subprocess.getoutput("sudo "+sys.argv[0]+" replace_autologin_script")

    self.destroy()



#r=subprocess.getoutput('whoami')
#if r!="root":
#  subprocess.Popen('sudo '+sys.argv[0],shell=True)
#  exit(0)
  
#installwin=InstallWindow()
get_current_data()

if USERNAME=="root":
  print("Usage: "+sys.argv[0]+" <user>");
  sys.exit()
  
if REALCURRENTUSER=="root":
  win = MainWindow()
else:
  win = AuthWindow()

win.connect("destroy", Gtk.main_quit)
win.show_all()

Gtk.main()