#!/usr/bin/env bash

## of-settings v1.16 (31st March 2026)
##  Bundles a bunch of handy settings into one place.

usage() {
	echo "Usage: $0 <option> [options]"
	echo
	echo "  autologin [user]            :  Enables or disables automatic login on tty1."
	echo "  autoxinit [user]            :  Enables or disables running Xserver at boot as <user> with systemd."
	echo "  autoxrun <user> <cmd>       :  Command run when Xserver started as <user> (~/.xinitrc)."
	echo "  grubquiet <enable|disable>  :  Quiet GRUB prints nothing to the screen."
	echo "  locale <locale>             :  Sets system locale (e.g. en_GB.UTF-8). No argument shows current."
	echo "  rootssh <enable|disable>    :  Allows password-based authentication for root over SSH."
	echo "  splash <name>               :  Sets splash screen theme and rebuilds initramfs. No name disables."
	echo "  timezone <timezone>         :  Sets system timezone (e.g. Europe/London). No argument shows current."
	echo "  xdefaults                   :  Sets OpenFrame system defaults for Xserver."
	echo
	exit 1
}

if [ $# -lt 1 ] || [[ "$1" == "-h" ]] || [[ "$1" == "--help" ]]; then
	usage
fi

if [ "$(id -u)" -ne 0 ]; then
	echo "You need to run this with superuser privileges. Try 'sudo $0'."
	exit 1
fi

case "${1}" in


	# Enables or disables automatic login on tty1 via getty.
	autologin)

		AUTOLOGINUSER="${2}"

		[ ! -d /etc/systemd/system/getty@tty1.service.d ] && mkdir -p /etc/systemd/system/getty@tty1.service.d

		if [[ "$AUTOLOGINUSER" != "" ]]; then

			echo -n "Enabling auto-login for user '$AUTOLOGINUSER'..."
			cat > /etc/systemd/system/getty@tty1.service.d/autologin.conf << EOF
[Service]
ExecStart=
ExecStart=-/usr/sbin/agetty -a $AUTOLOGINUSER --noclear %I \$TERM
EOF

		else

			echo -n "Disabling auto-login..."
			rm -f /etc/systemd/system/getty@tty1.service.d/autologin.conf

		fi

		echo " done."

	;;


	# Enables or disables starting Xserver as given user at boot.
	autoxinit)

		if [ $# -eq 2 ]; then

			# Check whether the given user exists.
			if ! getent passwd "${2}" &>/dev/null; then
				echo "Cannot find user '${2}'."
				exit 1
			fi

			# Check whether X.Org Server is installed.
			if [ ! -x /usr/bin/xinit ]; then
				echo "Xserver is not installed. Try 'of-install xserver' first."
				exit 1
			fi

			# Install service if user and Xserver exist.
			echo "Enabling Xserver start as '${2}' by systemd..."
			cat > /etc/systemd/system/startx.service << EOF
[Unit]
Description=Start X server on tty1
After=systemd-user-sessions.service
Before=getty@tty1.service

[Service]
User=${2}
ExecStart=/usr/bin/xinit -- :0 vt1 -nolisten tcp
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF
			systemctl enable startx.service
			exit 0

		else

			if [ -f /etc/systemd/system/startx.service ]; then

				echo "Disabling Xserver start by systemd..."
				systemctl disable startx.service
				rm /etc/systemd/system/startx.service

			fi

			exit 0

		fi

	;;


	# Command to run when Xserver is started as a given user (uses ~/.xinitrc).
	autoxrun)

		if [ "$#" -ne 3 ]; then

			usage

		else

			TARGETUSER="${2}"
			TARGETCMD="${3}"
			TARGETHOME="$(getent passwd "$TARGETUSER" | cut -d: -f6)"

			if [ -d "$TARGETHOME" ]; then

				if [ -f "$TARGETHOME/.xinitrc" ]; then
					echo "Backing up existing .xinitrc to $TARGETHOME/.xinitrc.bak."
					mv "$TARGETHOME/.xinitrc" "$TARGETHOME/.xinitrc.bak"
				fi

				echo -n "Writing $TARGETHOME/.xinitrc..."
				cat > "$TARGETHOME/.xinitrc" << EOF
export DISPLAY=:0.0
setterm -blank 0 -powersave off -powerdown 0
xset dpms 0 0 0 s off
$TARGETCMD || /usr/bin/xterm
EOF
				chown $TARGETUSER:$TARGETUSER "$TARGETHOME/.xinitrc"
				echo " done."
				exit 0

			else

				echo "No home directory found for user '$TARGETUSER'."
				exit 1

			fi

		fi

	;;


	# Silent GRUB prints nothing to the screen.
	grubquiet)

		if [[ "${2}" == "" ]] || [[ "${2}" == "enable" ]] || [[ "${2}" == "1" ]]; then

			echo -n "Enabling '${1}'..."
			printf 'fs1:grubq\nfs0:grubq\n' > /boot/boot.nsh

		else

			echo -n "Disabling '${1}'..."
			printf 'fs1:grub\nfs0:grub\n' > /boot/boot.nsh

		fi

		echo " done."
		exit 0

	;;


	# Allows password-based authentication for root over SSH.
	rootssh)

		PRSMSG="# Allows password-based authentication for root over SSH."
		PRSSET="PermitRootLogin yes"
		PRSCFG="/etc/ssh/sshd_config"

		if [[ "${2}" == "" ]] || [[ "${2}" == "enable" ]] || [[ "${2}" == "1" ]]; then

			echo -n "Enabling '${1}'..."

			if grep -q "$PRSSET" "$PRSCFG"; then
				echo " already enabled."
				exit 1
			fi

			printf '\n%s\n%s\n' "$PRSMSG" "$PRSSET" >> "$PRSCFG"

		else

			echo -n "Disabling '${1}'..."
			sed -i "/$PRSMSG/d" "$PRSCFG"
			sed -i "/$PRSSET/d" "$PRSCFG"
			perl -i -0pe 's/\n+$/\n/' "$PRSCFG"

		fi

		systemctl restart sshd.service

		echo " done."
		exit 0

	;;


	# Sets the splash screen theme and rebuilds initrd.
	splash)

		GRUBCFG=$(grep vmlinuz /boot/grub.cfg)
		PLYMOUTHTHEMESLOC="/usr/share/plymouth/themes"

		if [[ "${2}" != "" ]]; then

			# Check we've been given a valid theme name.
			if [ ! -d "$PLYMOUTHTHEMESLOC/${2}" ]; then

				echo "Theme '${2}' not found in $PLYMOUTHTHEMESLOC. Available themes are:"
				echo

				for d in /usr/share/plymouth/themes/*/; do
					basename "$d"
				done

				exit 1

			else

				PLYMOUTHCURRENTTHEME=$(update-alternatives --get-selections | grep default.plymouth)

				# Make sure we have the 'splash' option in GRUB config.
				[[ "$GRUBCFG" =~ "splash" ]] || sed -i "s,$GRUBCFG,$GRUBCFG splash,g" /boot/grub.cfg

				if [[ "$PLYMOUTHCURRENTTHEME" =~ "${2}.plymouth" ]]; then

					echo "Theme '${2}' is already selected."
					exit 1

				else

					echo -n "Configuring splash theme '${2}'..."
					update-alternatives --remove-all default.plymouth 2>/dev/null
					update-alternatives --remove-all text.plymouth 2>/dev/null
					update-alternatives --install /usr/share/plymouth/themes/default.plymouth default.plymouth /usr/share/plymouth/themes/"${2}"/"${2}".plymouth 100 &>/dev/null

					echo -n " updating initramfs..."
					update-initramfs -u &>/dev/null

				fi

			fi

		else

			echo -n "Disabling splash screens..."
			[[ "$GRUBCFG" =~ "splash" ]] && sed -i "s, splash,,g" /boot/grub.cfg

		fi

		echo " done."
		exit 0

	;;


	# Sets the system locale.
	locale)

		if [[ "${2}" == "" ]]; then

			echo "Current locale:"
			localectl status | grep "System Locale"
			exit 0

		fi

		LOCALE="${2}"

		if ! locale -a 2>/dev/null | grep -qx "${LOCALE}"; then
			echo -n "Generating locale '${LOCALE}'..."
			sed -i "s/^# *\(${LOCALE}\)/\1/" /etc/locale.gen
			locale-gen "${LOCALE}" || { echo " failed."; exit 1; }
			echo " done."
		fi

		echo -n "Setting locale to '${LOCALE}'..."
		update-locale LANG="${LOCALE}"
		echo " done."
		echo "Log out and back in for the change to take effect."
		exit 0

	;;


	# Sets the system timezone.
	timezone)

		if [[ "${2}" == "" ]]; then

			echo "Current timezone:"
			timedatectl status | grep "Time zone"
			exit 0

		fi

		TIMEZONE="${2}"

		if [ ! -f "/usr/share/zoneinfo/${TIMEZONE}" ]; then
			echo "Timezone '${TIMEZONE}' not found. Check /usr/share/zoneinfo/ for valid options."
			exit 1
		fi

		echo -n "Setting timezone to '${TIMEZONE}'..."
		timedatectl set-timezone "${TIMEZONE}"
		echo " done."
		exit 0

	;;


	# Sets OpenFrame system defaults for Xserver.
	xdefaults)

		echo -n "Configuring Xserver defaults..."
		cat > /etc/X11/app-defaults/XTerm << 'EOF'
*xterm*geometry: 132x36+0+0
*xterm*background: black
*xterm*foreground: lightgray
EOF
		cat > /etc/X11/Xwrapper.config << 'EOF'
allowed_users = anybody
needs_root_rights = yes
EOF
		echo " done."
		exit 0

	;;


	*)
		echo "No '${1}' setting found."
		exit 1
	;;

esac
