#!/bin/bash

. $CONFIG_DIRECTORY/config
. $MODULES_DIRECTORY/config
. $MODULES_DIRECTORY/functions
. $MODULES_DIRECTORY/common.dml
. $MODULES_DIRECTORY/moduser.dml

get_username()
{
	ok=0;

	eval `echo "$DIALOG_get_username" | $DML`;
	if [ $res -eq 2 ]; then return 0; fi

	while [ $ok -eq 0 ]; do
		ok=1;
		if [ ! "`$GREP -E "^$username:" /etc/passwd`" ]; then
			eval `printf "$DIALOG_user_unknown" "$username" | $DML`;
			if [ $res -eq 2 ]; then return 0; fi
			ok=0;
		fi
	done

	return 1;
}

get_modifications()
{
	load_user_data "$username"

	fullname=$_comment
	
	eval `printf "$DIALOG_choose_action" "$username" "$fullname" | $DML`
	if [ $res -eq 3 ]; then return 0; fi
	
	case $res in
		# Password change
		1)
			eval `echo "$DIALOG_enter_password" | $DML`;
			if [ $res -eq 2 ]; then return 1; fi
			ok=0;
			while [ $ok -eq 0 ]; do
			ok=1;
			if [ ! "`echo $pass | $GREP -E \"^.{6,}\"`" ]; then
				eval `echo "$DIALOG_password_incorrect" | $DML`;
				if [ $res -eq 2 ]; then return 1; fi
				ok=0;
			fi
			if [ $ok -eq 1 ] && [ "$pass" != "$passverify" ]; then
				eval `echo "$DIALOG_passwords_dont_match" | $DML`;
				if [ $res -eq 2 ]; then return 1; fi
				ok=0;
			fi
			done
			update="password"
		;;
		# Fullname change
		2)
			eval `printf "$DIALOG_enter_fullname" "$fullname" | $DML`;
			if [ $res -eq 2 ]; then return 1; fi
			ok=0;
			while [ ! "`echo \"$fullname\" | $GREP -E -v \";|,|:\"`" ]; do
				eval `printf "$DIALOG_enter_fullname" "$fullname" | $DML`;
				if [ $res -eq 2 ]; then return 1; fi
			done
			update="fullname"
		;;
	esac
	return 1;
}

set_modifications()
{
	case $update in
		password)
			output=`(echo $username:$pass | $CHPASSWD) 2> /dev/null`
		        RETVAL=$?
	        	if [ $RETVAL -gt 0 ]; then
	                	eval `echo "$DIALOG_chpasswd_error" | $DML`
		                return 0;
		        fi
			log_action "Password for $username changed"
		;;
		fullname)
			output=`$USERMOD -c "$fullname" $username`;
			RETVAL=$?
			if [ $RETVAL -gt 0 ]; then
				eval `echo "$DIALOG_usermod_error" | $DML`
				return 0;
			fi
			log_action "Fullname for $username changed"
		;;
	esac;

	return 0;
}

get_username
RETVAL=$?

if [ $RETVAL -eq 0 ]; then exit; fi

finish=0;

while [ $finish -eq 0 ]; do
	get_modifications
	RETVAL=$?
	if [ $RETVAL -eq 0 ]; then finish=1; fi
	if [ $finish -ne 1 ]; then set_modifications; fi
done

