#!/bin/bash

export DIALOGRC=/tmp/dialogrc

set_rootpasswd() {
source /etc/profile >/dev/null 2>&1

dialog --title "Root Password" --msgbox "\nThere is currently no password set on the system for the (root) account. It is recommended that you set on now so that it is active the first time the machine is rebooted. This is espacially important if you're using a network enabled kernel and the machine is on an Internet connected Lan." 10 65

while true; do
    PASSWORD1=$(dialog --stdout --insecure --passwordbox "Enter password:" 8 40)
    PASSWORD2=$(dialog --stdout --insecure --passwordbox "Confirm password:" 8 40)

    if [[ -z "$PASSWORD1" ]]; then
        dialog --msgbox "Password cannot be empty." 8 40
    elif [[ "$PASSWORD1" != "$PASSWORD2" ]]; then
        dialog --msgbox "Passwords do not match. Try again." 8 40
    else
	    echo "root:$PASSWORD1" | /usr/sbin/chpasswd >/dev/null 2>&1 
   	    dialog --msgbox "User 'Root' created successfully." 8 40
        break
    fi
done
}


create_reguser() {
source /etc/profile >/dev/null 2>&1

dialog --title "User Account" --msgbox "\n\nWe will now set up an account for a regular user. Another user accounts can be set up after installation. We need to now under which name this user will login to access Snukware." 10 65

while true; do
    LOGIN=$(dialog --stdout --inputbox "Enter new username:" 8 40) 

    if [[ -z "$LOGIN" ]]; then
        dialog --msgbox "Password cannot be empty, try it again" 8 40
    else
        break
    fi
done

while true; do
    PASSWORD1=$(dialog --stdout --insecure --passwordbox "Enter password:" 8 40)
    PASSWORD2=$(dialog --stdout --insecure --passwordbox "Confirm password:" 8 40)

    if [[ -z "$PASSWORD1" ]]; then
        dialog --msgbox "Password cannot be empty." 8 40
    elif [[ "$PASSWORD1" != "$PASSWORD2" ]]; then
        dialog --msgbox "Passwords do not match. Try again." 8 40
    else
        break
    fi
done

if useradd -m -g users -G wheel,audio,video,seat,plugdev,netdev,power,input,lp,scanner "$LOGIN"; then
   echo "$LOGIN:$PASSWORD1" | /usr/sbin/chpasswd >/dev/null 2>&1 
   dialog --msgbox "User '$LOGIN' created successfully." 8 40
   if [ ! -d /var/lib/systemd/linger ]; then
	mkdir -p /var/lib/systemd/linger
	touch /var/lib/systemd/linger/"$LOGIN"
	else
	touch /var/lib/systemd/linger/"$LOGIN"
   fi
else
   dialog --msgbox "Failed to create user." 8 40
fi

clear
}


set_rootpasswd 
create_reguser

unset DIALOGRC

clear
