#!/bin/bash

# This script manages the setting of a password.  
# It is mostly intended during Slint installlation.
# Kind of a stripped down usersetup as found in salixtools, thus
# added to the salixtols package customized for Slint.
# This will ease the management of translations
# Didier Spaier <didier~at~slint~dot~fr>

# Translations only work with utf8 locales
if ! locale -k charmap|grep -q UTF-8 ; then
	LANG=C
fi

# Gettext internationalization
export TEXTDOMAIN="usersetup"
export TEXTDOMAINDIR="/usr/share/locale"
. gettext.sh

# check for root privileges
if [ "$UID" != "0" ]; then
	echo "`eval_gettext 'You need root privileges to run this'`"
	exit 1
fi

# Password dialog
passbox(){
	DIALOG='dialog --stdout --insecure --fixed-font --no-cancel --smooth --passwordbox'
	pw="$(${DIALOG} "${1}" 0 0)"
	echo -n "$pw"
}


# Password checking
changepw(){

maxcount=5
minlength=5

count=1 ; pw='_'
while [ "${pw}" != "${password}" ]; do
	password="" ; pw='_'
	if [ $count -gt $maxcount ]; then
		echo -n ""
		break
	fi

	message="`eval_gettext 'Enter password for account'` ${1}...  "
	[ $count -ge 2 ] && message="`eval_gettext 'Passwords do not match, please try again...'`"
	while [ "$(echo -n "${pw}" | wc --chars)" -lt ${minlength} ]; do
		pw="$(passbox "${message}")"
		message="`eval_gettext 'Password is too short (${minlength} chars minimum), please try another one...'`  "		
	done
	password="$pw" ; pw='_'
	message="`eval_gettext 'Enter password again for account'` ${1}...  "
	pw="$(passbox "${message}")"
	
	count=$((count+1))

done

echo -n $password
}

# Change password
	DIALOG="dialog"
    user="root"
	
	[ "$user" ] && pass="$(changepw ${user})"
	if [ ! "$pass" ] ; then
		${dialog} --msgbox "`eval_gettext 'Failed to set password for account'` \"${user}\"  " 0 0
	else
		# echo "${user}:${pass}"
		[ "$user" ] && echo "${user}:${pass}" | chpasswd
	fi
