#!/bin/sh

dotsrepo="https://github.com/ssnailed/dotfiles"
dotsbranch="main"

error() {
	# Log to stderr and exit with failure.
	printf "%s\n" "$1" >&2
	exit 1
}

welcome() {
	whiptail \
		--title "Welcome!" \
		--msgbox \
		"Welcome!\\n\\nThis script will automatically install a fully-featured Linux desktop with DWM and my dotfiles." \
		10 60
}

getlogin() {
	# Prompts user for new username an password.
	name=$(
		whiptail \
			--inputbox "First, please enter a name for the user account." \
			10 60 3>&1 1>&2 2>&3 3>&1
	) || exit 1
	while ! echo "$name" | grep -q "^[a-z_][a-z0-9_-]*$"; do
		name=$(
			whiptail \
				--nocancel \
				--inputbox "Username not valid. Give a username beginning with a letter, with only lowercase letters, - or _." \
				10 60 3>&1 1>&2 2>&3 3>&1
		)
	done
	pass1=$(
		whiptail \
			--nocancel \
			--passwordbox "Enter a password for that user." \
			10 60 3>&1 1>&2 2>&3 3>&1
	)
	pass2=$(
		whiptail \
			--nocancel \
			--passwordbox \
			"Retype password." \
			10 60 3>&1 1>&2 2>&3 3>&1
	)
	while ! [ "$pass1" = "$pass2" ]; do
		unset pass2
		pass1=$(
			whiptail \
				--nocancel \
				--passwordbox "Passwords do not match.\\n\\nEnter password again." \
				10 60 3>&1 1>&2 2>&3 3>&1
		)
		pass2=$(
			whiptail \
				--nocancel \
				--passwordbox "Retype password." \
				10 60 3>&1 1>&2 2>&3 3>&1
		)
	done
}

usercheck() {
	if id -u "$name" >/dev/null 2>&1; then
		whiptail \
			--title "WARNING" \
			--yes-button "Continue" \
			--no-button "Cancel" \
			--yesno "\`$name\` already exists on this system.\\n\\nThis script will overwrite any conflicting dotfiles and change this user's password to the one you just gave." 14 70
	fi
}

sanitycheck() {
    while IFS=, read -r tag program comment; do
        case "$tag" in
            # "G") ;;
            "P") ;;
            "X") ;;
            *) error "Incorrect installation tag for $program in progs.csv" ;;
        esac
    done
}

rootcheck() {
    return "$(id -u)"
}

preinstall() {
	whiptail \
		--title "Confirmation" \
		--yes-button "Start Installation" \
		--no-button "Cancel" \
		--yesno "The rest of the installation is automated." \
		13 60 || clear && exit 1
	whiptail \
        --title "XBPS Updates" \
        --infobox "Updating XBPS Packages." \
        10 60
	xbps-install -Syu >/dev/null 2>&1
}

addlogin() {
	# Adds user `$name` with password $pass1.
	whiptail \
		--infobox "Adding user \"$name\"..." \
		7 50
	useradd -m -g wheel -s /bin/zsh "$name" >/dev/null 2>&1 ||
		usermod -a -G wheel "$name" &&
		mkdir -p /home/"$name" &&
		chown "$name":wheel /home/"$name"
    export HOME="/home/$name"
	export repodir="$HOME/.local/src"
	export dotsdir="$HOME/.dotfiles"
	mkdir -p "$repodir"
	chown -R "$name":wheel "$(dirname "$repodir")"
	echo "$name:$pass1" | chpasswd
	unset pass1 pass2
}

installxbps() {
	whiptail \
        --title "XBPS Installation" \
        --infobox "Installing \`$1\` ($n of $total). $1 $2" \
        9 70
	xbps-install -Sy "$1" >/dev/null 2>&1
}

# installgitmake() {
# 	progname="${1##*/}"
# 	progname="${progname%.git}"
# 	dir="$repodir/$progname"
# 	whiptail \
#         --title "Git Installation" \
# 		--infobox "Installing \`$progname\` ($n of $total) via \`git\` and \`make\`. $(basename "$1") $2" \
#         8 70
# 	sudo -u "$name" git -C "$repodir" clone --depth 1 --single-branch \
# 		--no-tags -q "$1" "$dir" ||
# 		{
# 			cd "$dir" || return 1
# 			sudo -u "$name" git pull --force origin main
# 		}
# 	cd "$dir" || exit 1
# 	make >/dev/null 2>&1
# 	make install >/dev/null 2>&1
# 	cd /tmp || return 1
# }

installpip() {
	whiptail \
        --title "Pip Installation" \
		--infobox "Installing the Python package \`$1\` ($n of $total). $1 $2" 9 70
	[ -x "$(command -v "pip")" ] || installpkg python-pip >/dev/null 2>&1
	yes | pip install "$1"
}

initnvim() {
    whiptail \
        --title "Installation" \
        --infobox "Bootstrapping neovim" \
        8 70
    nvim --headless +qa
}

installationloop() {
	total=$(wc -l <progs.csv)
	while IFS=, read -r tag program comment; do
		n=$((n + 1))
		echo "$comment" | grep -q "^\".*\"$" &&
			comment="$(echo "$comment" | sed -E "s/(^\"|\"$)//g")"
		case "$tag" in
            # "G") installgitmake "$program" "$comment" ;;
            "P") installpip "$program" "$comment" ;;
            "X") installxpbs "$program" "$comment" ;;
		esac
	done <progs.csv
}

pulldots() {
	whiptail \
        --infobox "Dowloading dotfiles" \
        7 60
	sudo -u "$name" \
        git -C "$dotsdir" \
        clone --depth 1 --no-tags -q --recurse-submodules \
		--single-branch -b "$dotsbranch" \
        "$dotsrepo"
}

initbootstrap() {
    for package in curl ca-certificates base-devel git ntp zsh; do
        whiptail \
            --title "Installation" \
            --infobox "Installing \`$package\` which is required to install and configure other programs." \
            8 70
        install-xbps "$package"
    done
    whiptail \
        --title "Installation" \
        --infobox "Making some required configurations." \
        8 70
    trap 'rm -f /etc/sudoers.d/bootstrap-temp' HUP INT QUIT TERM PWR EXIT
    echo "%wheel ALL=(ALL) NOPASSWD: ALL" >/etc/sudoers.d/bootstrap-temp
    sed -i "s/-j2/-j$(nproc)/;/^#MAKEFLAGS/s/^#//" /etc/makepkg.conf
}

synctime() {
    whiptail \
        --title "Installation" \
        --infobox "Synchronizing system time to ensure successful and secure installation of software..." \
        8 70
    ntpdate "0.us.pool.ntp.org" >/dev/null 2>&1
}

finalize() {
    whiptail \
        --title "Installation" \
        --infobox "Cleaning up..." \
        8 70
    mkdir -p "$HOME/.local/share/virtualenv"
    mkdir -p "$HOME/.local/share/gnupg"
}

goodbye() {
	whiptail \
        --title "All done!" \
        --msgbox "Unless this script has bugs (contact me at luca@snaile.de) the installation is finished\\n\\n\
To run the new graphical environment, log out and log back in as your new user, then run the command \"startgraphical\" to start the graphical environment (it will start automatically in tty1)." \
    13 80
}

### EXECUTION STARTS HERE ###

sanitycheck

rootcheck || error "Make sure this script is running as root. (Was run as user \`$(id -un $?)\`)"

welcome || error "User exited."

getlogin || error "User exited."

usercheck || error "User exited."

preinstall || error "User exited."

addlogin || error "Error adding username and/or password."

initbootstrap

synctime

installationloop

pulldots

initnvim

finalize

goodbye