#!/bin/bash

. /usr/share/groovix/global.conf

# per user settings
if [ -e /etc/groovix/peruser/$GUNAME/groovix.conf ] ; then
        . /etc/groovix/peruser/$GUNAME/groovix.conf
fi

#set -x


rm -f ~/.xlockpw

if [ -z "$GX_SCREEN_LOCK_MAX_MINUTES" ] ; then
	GX_SCREEN_LOCK_MAX_MINUTES=5
fi

#TODO: 
#make it so staff password will unlock: /etc/xlock.staff ?
#       - could always write a pam module like pacauth


#do they already have a pin set or do we need to ask for one now?
if [  "$GX_SCREEN_LOCK_ALWAYS_ASK_FOR_PIN" = true ] ; then
	PWRC=0
else
	#determine automatically
	#how to tell if we should ask for a password?
	# run pacauth.checkonly and see if the return message includes "passwordless login matched"
	pacauth.checkonly $USER "" | grep "passwordless login matched"
	PWRC=$?
fi

if [ "$PWRC" -eq 0 ] ; then
	NEWPW=$(zenity --width=400 --title "Screen Locking" --text "\
You must create a password/pin to lock the screen.  The password/pin may
contain any number of letters, numbers, or special characters (but not spaces).

If you forget your password/pin you will not be able to unlock the screen.

Your session will be closed if you do not return to your session within $GX_SCREEN_LOCK_MAX_MINUTES minutes.

Please enter a password/pin that you will use to unlock the screen: \
" --entry)
	ZRC=$?
	if [ $ZRC -ne 0 ] ; then
		exit 0
	fi
        #no spaces.  pretty much everything else should be ok: in pam module: re.match('^[a-zA-Z0-9\_\.\-\@\~\!\#\$\%\^\&\*\(\)]*$',submitted_pin):
	PATTERN=" "
	if [ -z "$NEWPW" ] || [[ $NEWPW =~ $PATTERN ]] ; then
		zenity --width=400 --error  --text "Invalid password/pin.\nThe screen will not be locked."
		exit 0
	fi
	#echo usermod --password $(echo "$NEWPW" | mkpasswd -s -H MD5) $(whoami)
	#usermod --password $(echo "$NEWPW" | mkpasswd -s -H MD5) $(whoami)

	echo "$NEWPW" > ~/.xlockpw
	chmod 600 ~/.xlockpw


else
	#we already have password of some sort set, proceed
	zenity --width=400 --title "Screen Locking" --text "\
You will need to know your password/pin to unlock the screen (the same one you used to log in).

Your session will be closed if you do not return to your session within $GX_SCREEN_LOCK_MAX_MINUTES minutes.

Do you want to lock the screen now? \
" --question
	if [ $? -ne 0 ]  ; then
		exit 0
	fi
	
fi

#this updates the screen lock message and after the specified max locking time the lock will be cancelled
groovix-screen-lock-timer $GX_SCREEN_LOCK_MAX_MINUTES &

xlock -font "-*-fixed-*-*-*-*-18-*-*-*-*-*-*-*"  -password "Password/Pin: " -username "User: " -info "Enter your password/pin and hit enter to unlock the screen." -erasemode no_fade +description +mousemotion -mode marquee -mono +usefirst -icongeometry 0x0 -messagefile ~/.groovix-screen-lock-time

echo xlock done
rm -f ~/.xlockpw
killall groovix-screen-lock-timer
