#!/bin/bash

BACKTITLE="Snukware Installer"


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

export DIALOGRC=/tmp/dialogrc

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

while true; do
    if ! PASSWORD1=$(dialog --stdout --insecure --backtitle "$BACKTITLE" --passwordbox "Enter password:" 8 40); then
        continue
    fi

    if ! PASSWORD2=$(dialog --stdout --insecure --backtitle "$BACKTITLE" --passwordbox "Confirm password:" 8 40); then
        continue
    fi

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


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

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

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

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

while true; do
    if ! PASSWORD1=$(dialog --stdout --insecure --backtitle "$BACKTITLE" --passwordbox "Enter password:" 8 40); then
        continue
    fi

    if ! PASSWORD2=$(dialog --stdout --insecure --backtitle "$BACKTITLE" --passwordbox "Confirm password:" 8 40); then
        continue
    fi

    if [[ -z "$PASSWORD1" ]]; then
        dialog --backtitle "$BACKTITLE" --msgbox "Password cannot be empty." 8 40
    elif [[ "$PASSWORD1" != "$PASSWORD2" ]]; then
        dialog --backtitle "$BACKTITLE" --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
   dialog --backtitle "$BACKTITLE" --msgbox "User '$LOGIN' created successfully." 8 40
else
   dialog --backtitle "$BACKTITLE" --msgbox "Failed to create user." 8 40
fi

clear
}


set_rootpasswd
create_reguser

unset DIALOGRC

clear
