#!/bin/bash

##################################################################################
##										##
## 			Forma de uso de este script				##
##										##
##    Inicialmente se ejecuta sin privilegios, en su momento solicitará		##
##    permisos de root (con gksudo)						##
## 										##
##    Este script fué realizado por Miguel Anxo Bouzada para el equipo		##
##    de GALPon MiniNo <minino@galpon.org> http://minino.galpon.org 		##
##										##
##    Este script se publica SIN NINGUNA GARANTIA y bajo la Licencia Pública	##
##    General GNU versión 3, publicada por la Free Software Fundation.		##
##										##
##    Depende del fichero anexo «libminino-login» que debe estar en /usr/lib	##
##    y de los ficheros .mo que se encuentran en la carpeta «po», que deben 	##
##    estar en /usr/share/locale/IDIOMA/LC_MESSAGES				##
##										##
##################################################################################

export TEXTDOMAIN="minino-login"
export TEXTDOMAINDIR="/usr/local/share/locale"

# Para lightdm
#currentUser=`cat /etc/lightdm/lightdm.conf | grep autologin-user= | cut -c16-32`
#sed -i "s+autologin-user=$currentUser+autologin-user=$newUser+" /etc/lightdm/lightdm.conf

# Directorio final
DIR="/usr/local/lib"

# Ponemos a cero la marca de contraste
CONTRAST=""

function changeUser(){
	# Buscamos cual es el usuario que tiene asignado el acceso automático en este momento
	currentUser=`cat /etc/inittab | grep 1:2345:respawn: | cut -f3 -d" "`

	# Si en la posición de la búsqueda nos aparece «tty1» quiere decir
	# que el S.O. está en acceso manual, solicitandu usuario/passwd por
	# lo que usamos el usuario actual del sistema como referencia
	[ "$currentUser" == "tty1" ] && currentUser="$(gettext "None")" 

	newUser=$(yad --title "$(gettext "Auto Login")" --entry --entry-text "$USER" --entry-label " $(gettext "User:")" \
		--image user_auth \
		--text " $(gettext "Currently, auto login default user is:") \n →\t<b>$currentUser</b>\n\n $(gettext "Enter the <b>user name</b> that will start \n the system automatically:") ")

	[ $? != 0 ] && exit

	[ "$newUser" == "$currentUser" ] && yad --title "$(gettext "Change User")" \
		--image user_auth --button "$(gettext "_Go Back")":2 --button gtk-cancel:252 \
		--text "$(gettext " The new user and the default user are the same. \n Go back and enter a diferent username, \n or Cancel the process.")"

	[ $? = 2 ] && changeUser
	[ $? == 252 ] && exit

	# Buscamos si existe, en /etc/group, el usuario creado
	readUser=`cat /etc/group | grep $newUser:x:10 | cut -f1,2 -d0`
	[ "$readUser" == "$newUser:x:10" ] && State="EXIST" ||  State="NOT-EXIST"

	if [ "$State" == "EXIST" ]; then
		yad --title  "$(gettext "Auto Login")" --image user_auth \
		--button "$(gettext "Change _User")":2 --button gtk-cancel:1 --button gtk-ok:0 \
		--text " $(gettext "Are you sure? Next time, the system will NOT ask you for \n a password and will start automaticaly with the user:") \n\n →\t<b><i>$newUser</i></b>\n"
		ret=$?

		[ $ret = 2 ] && changeUser

		if [ $ret = 0 ]; then
	   	    if [ "$CONTRAST" == "CONTRAST" ]; then
			gksudo $DIR/libminino-login AutoLogin  $newUser
	    	    else
			gksudo $DIR/libminino-login ChangeUser $newUser $currentUser
	    	    fi
		else
	    	    exit
		fi

	elif [ "$State" == "NOT-EXIST" ]; then
		yad --title  "$(gettext "Auto Login")" --image user_auth \
		--button "$(gettext "_Go Back")":2 --button gtk-cancel:1  --title  "$(gettext "Auto Login")" \
		--text " $(gettext "The user") <b><i>$newUser</i></b> $(gettext "<b>DOESN'T EXISTS</b> in this System, and it is \n <b>not posible</b> set it for auto-login. \n\n Process is ignored. \n\n You can back to choose a new user, or Cancel \n the process and create a new user and, then, \n try it again.")"

		[ $? = 2 ] && changeUser || exit
	fi
}

function changeLoginMode(){

	actualMode=`cat /etc/inittab | grep 1:2345:respawn: | cut -f2 -d/`

	ACTION=$(yad --title "$(gettext "Login")" \
		--text " $(gettext "Choose the option you want \n to configure. ") " \
		--width 340 --image user_auth --list --print-column 1 ---no-headers \
		--column control --column accion:tip --hide-column 1 \
		"auto" "$(gettext "Auto Login (without password)")" \
		"manual" "$(gettext "Manual Login (with password)")" )

		[ $? != 0 ] && exit

		if [ "$ACTION" == "auto|" ]; then
		    if [ "$actualMode" == "bin" ]; then
			yad --title  "$(gettext "Change User")" --image user_auth --button "$(gettext "Change _User")":2 --button gtk-ok:0 \
			    --text " $(gettext "The system IS ALREADY configurated to \n access automatically WITHOUT a password. ") "
			[ $? = 2 ] && changeUser || exit
		    else
			# Creo una variable de contraste para que despues de usar la
			# función changeUser nos envíe a la función libminino-login
			CONTRAST="CONTRAST"
			changeUser
		    fi
		elif [ "$ACTION" == "manual|" ]; then
		    if [ "$actualMode" == "sbin" ]; then
			yad --title "$(gettext "Change User")" --image user_auth --button gtk-ok:0 \
			    --text " $(gettext "The system IS ALREADY set to access \n through an interface by entering a password.") "
			exit
		    else
			gksudo $DIR/libminino-login ManualLogin
		    fi
		else
		    exit
		fi
}

# Select Login Mode
# Select Auto Login User

OPTION=$(yad --title "$(gettext "Login")" \
	     --text " $(gettext "Choose the option you want to configure. ") " \
	     --image user_auth --list --print-column 1 --no-headers \
	     --width 390 --column control --column accion:tip --hide-column 1 \
	     "login" "$(gettext "Choose the access mode")" \
	     "change" "$(gettext "Choose a diferent user for auto login")" )

[ $? != 0 ] && exit

[ "$OPTION" == "login|" ] && changeLoginMode

if [ "$OPTION" == "change|" ]; then 
	# Buscamos cual es el usuario que tiene asignado el acceso automático en este momento
	currentUser=`cat /etc/inittab | grep 1:2345:respawn: | cut -f3 -d" "`
	# Si en la posición de la búsqueda nos aparece «tty1» quiere decir que el modo
	# de acceso es «a través de interface» ó «manual»
    if [ "$currentUser" == "tty1" ]; then
	yad --title "$(gettext "Change User")" --image user_auth --button gtk-ok:0 \
	    --text " $(gettext "The system is not set with auto login and therefore, \n it is not possible to change the auto-login user. \n Change the access mode first. ") "
	exit
    else
	changeUser
    fi
else
    exit
fi
