#!/bin/bash

ask_reboot () {
    echo "The wizard will be launched on reboot to rename the user."
    read -n1 -p "Would you like to reboot now? [Y/n] " response
    echo
    case "$response" in
       [yY]) return 0;;
       ?) return 1;;
    esac
}

if [ "$(id -u)" != "0" ]; then
    echo "Please run with 'sudo': sudo rename-user" >&2
    exit 1
fi

USER=${SUDO_USER:-$(who -m | awk '{ print $1 }')}
ADDITIONAL=" --useronly $USER"
RESTART=""

while getopts 'frs' c; do
    case $c in
        f) ADDITIONAL="" ;;
        r) RESTART=True ;;
        s) RESTART=False ;;
    esac
done

echo "Preparing to run wizard - please wait..."

if [ "$(raspi-config nonint get_autologin)" -eq 0 ]; then
    mkdir -p /var/lib/userconf-pi
    touch /var/lib/userconf-pi/autologin
elif [ -d /var/lib/userconf-pi ]; then
    rm -f /var/lib/userconf-pi/autologin
    rmdir --ignore-fail-on-non-empty /var/lib/userconf-pi
fi

if [ "$(raspi-config nonint get_boot_cli)" -ne 0 ]; then
    WIZ_USER=rpi-first-boot-wizard
    FIRSTUSER="$(getent passwd 1000 | cut -d: -f1)"
    while [ "$USER" = "root" ] || ! getent passwd "$USER" >/dev/null; do
        if ! USER=$(whiptail --inputbox "rename-user could not determine the default user.\\n\\nWhat user should these settings apply to?" 20 60 "$FIRSTUSER" 3>&1 1>&2 2>&3); then
            echo "rename-user could not determine which user to rename" >&2
            exit 1
        fi
    done

    # create the first boot user
    if ! getent passwd "$WIZ_USER" >/dev/null; then
        adduser "$WIZ_USER" --gecos ',,,,' --home "/home/$WIZ_USER" --add_extra_groups --quiet --disabled-password --system --shell /bin/bash > /dev/null
        adduser "$WIZ_USER" input --quiet > /dev/null
        adduser "$WIZ_USER" netdev --quiet > /dev/null
        adduser "$WIZ_USER" video --quiet > /dev/null
    fi
    echo "$WIZ_USER ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/010_wiz-nopasswd

    # create the wizard autostart...
    cat <<- EOF > /etc/xdg/autostart/piwiz.desktop
		[Desktop Entry]
		Type=Application
		Name=Raspberry Pi First-Run Wizard
		Exec=piwiz$ADDITIONAL
		StartupNotify=true
	EOF

    SUDO_USER="$WIZ_USER" raspi-config nonint do_boot_behaviour B4
fi

cat <<- EOF > /etc/ssh/sshd_config.d/rename_user.conf
	Banner /usr/share/userconf-pi/sshd_banner
EOF
if systemctl --quiet is-active ssh; then
	systemctl --quiet reload ssh
fi

systemctl --quiet disable getty@tty1
systemctl --quiet enable userconfig

sync

if [ "$RESTART" = "True" ] || [ "$RESTART" != "False" ] && ask_reboot; then
    reboot
else
    echo "Reboot to rename user or run 'sudo cancel-rename USER' to cancel."
fi
