#!/bin/bash
# Applies the setup file l4s-image-config writes to switchroot/<distro>/ on the SD card.
set -u

conf=${1:-/boot/switchroot/l4s-setup.conf}
[ -f "$conf" ] || exit 0

log() { echo "l4s-setup: $*"; }

host='' root_hash='' user='' user_hash='' user_sudo=1 permit='' pwauth=''
keys=() ssids=() psks=()

while IFS= read -r line || [ -n "$line" ]; do
	line=${line%$'\r'}
	case $line in
	'' | '#'*) continue ;;
	*=*) ;;
	*) log "ignoring malformed line"; continue ;;
	esac
	val=${line#*=}
	case ${line%%=*} in
	HOSTNAME) host=$val ;;
	ROOT_PASSWORD_HASH) root_hash=$val ;;
	USERNAME) user=$val ;;
	USER_PASSWORD_HASH) user_hash=$val ;;
	USER_SUDO) user_sudo=$val ;;
	SSH_KEY) keys+=("$val") ;;
	SSH_PERMIT_ROOT_LOGIN) permit=$val ;;
	SSH_PASSWORD_AUTH) pwauth=$val ;;
	WIFI_SSID) ssids+=("$val"); psks+=("") ;;
	WIFI_PSK) [ ${#ssids[@]} -gt 0 ] && psks[-1]=$val ;;
	*) log "ignoring unknown key ${line%%=*}" ;;
	esac
done < "$conf"
rm -f -- "$conf"

valid_hash() {
	[[ $1 =~ ^\$[0-9a-z]+\$[^:[:space:]]+$ ]]
}

keyfile_escape() {
	local s=${1//\\/\\\\}
	[ "${s:0:1}" = " " ] && s="\\s${s:1}"
	printf '%s' "$s"
}

ssid_value() {
	if [[ $1 =~ ^[A-Za-z0-9_.@+-]([A-Za-z0-9\ _.@+-]*[A-Za-z0-9_.@+-])?$ ]]; then
		printf '%s' "$1"
	else
		printf '%s' "$1" | od -An -v -tu1 | tr -s ' \n' ';' | sed 's/^;//'
	fi
}

add_wifi() {
	local ssid=$1 psk=$2 dir=/etc/NetworkManager/system-connections f
	if [ -z "$ssid" ] || [ ${#ssid} -gt 32 ]; then
		log "skipping invalid SSID"
		return
	fi
	if [ -n "$psk" ] && ! { [ ${#psk} -ge 8 ] && [ ${#psk} -le 63 ]; } && ! [[ $psk =~ ^[0-9a-fA-F]{64}$ ]]; then
		log "skipping $ssid: passphrase must be 8-63 characters"
		return
	fi
	f=$dir/$(printf '%s' "$ssid" | tr -c 'A-Za-z0-9._-' '_').nmconnection
	install -d -m 755 "$dir"
	(
		umask 077
		{
			printf '[connection]\nid=%s\nuuid=%s\ntype=wifi\nautoconnect=true\n\n' \
				"$(keyfile_escape "$ssid")" "$(cat /proc/sys/kernel/random/uuid)"
			printf '[wifi]\nmode=infrastructure\nssid=%s\n\n' "$(ssid_value "$ssid")"
			[ -n "$psk" ] && printf '[wifi-security]\nkey-mgmt=wpa-psk\npsk=%s\n\n' "$(keyfile_escape "$psk")"
			printf '[ipv4]\nmethod=auto\n\n[ipv6]\nmethod=auto\naddr-gen-mode=default\n'
		} > "$f"
	)
	chown 0:0 "$f"
	log "added Wi-Fi network $ssid"
}

set_hostname() {
	local new=$1 old
	if ! [[ $new =~ ^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?$ ]]; then
		log "skipping invalid hostname"
		return
	fi
	old=$(tr -d '[:space:]' < /etc/hostname 2>/dev/null)
	echo "$new" > /etc/hostname
	echo "$new" > /proc/sys/kernel/hostname
	if [ -n "$old" ] && [ "$old" != "$new" ] && [ -f /etc/hosts ]; then
		sed -E -i ":a; /^[[:space:]]*#/! s/(^|[[:space:]])$old(\.[^[:space:]]*)?([[:space:]]|$)/\1$new\2\3/; ta" /etc/hosts
	fi
	log "hostname $new"
}

set_user() {
	local g groups=() created=0
	if ! [[ $user =~ ^[a-z_][a-z0-9_-]{0,31}$ ]] || [ "$user" = root ]; then
		log "skipping invalid user name"
		return
	fi
	if [ -n "$user_hash" ] && ! valid_hash "$user_hash"; then
		log "ignoring invalid password hash for $user"
		user_hash=
	fi
	if id -u "$user" >/dev/null 2>&1; then
		[ -n "$user_hash" ] && usermod -p "$user_hash" "$user"
	else
		useradd -m -U -s /bin/bash ${user_hash:+-p "$user_hash"} "$user" || return
		created=1
	fi
	if [ "$user_sudo" = 1 ]; then
		for g in sudo wheel video audio input render; do
			getent group "$g" >/dev/null && groups+=("$g")
		done
		[ ${#groups[@]} -gt 0 ] && usermod -aG "$(IFS=,; echo "${groups[*]}")" "$user"
	fi
	if [ $created = 1 ] && [ -n "$user_hash" ]; then
		systemctl disable initial-setup.service 2>/dev/null
		rm -f /etc/reconfigSys
	fi
	log "user $user ready"
}

authorize_keys() {
	local who=$1 home uid gid k d
	home=$(getent passwd "$who" | cut -d: -f6)
	uid=$(id -u "$who" 2>/dev/null) || return
	gid=$(id -g "$who")
	[ -n "$home" ] || return
	d=$home/.ssh
	install -d -m 700 -o "$uid" -g "$gid" "$d"
	touch "$d/authorized_keys"
	for k in "${keys[@]}"; do
		[[ $k =~ ^(ssh-|ecdsa-|sk-) ]] || continue
		grep -qxF -- "$k" "$d/authorized_keys" || printf '%s\n' "$k" >> "$d/authorized_keys"
	done
	chown "$uid:$gid" "$d/authorized_keys"
	chmod 600 "$d/authorized_keys"
	log "authorized ${#keys[@]} key(s) for $who"
}

sshd_set() {
	local key=$1 val=$2 main=/etc/ssh/sshd_config dropin=/etc/ssh/sshd_config.d/00-l4s-setup.conf
	[ -f "$main" ] || return
	if grep -qiE '^Include[[:space:]]+/etc/ssh/sshd_config\.d/\*\.conf' "$main"; then
		touch "$dropin"
		sed -i "/^$key /d" "$dropin"
		echo "$key $val" >> "$dropin"
	else
		sed -i -E "/^[[:space:]]*#?[[:space:]]*${key}[[:space:]]/d" "$main"
		echo "$key $val" >> "$main"
	fi
	log "sshd $key $val"
}

[ -n "$host" ] && set_hostname "$host"

for i in "${!ssids[@]}"; do
	add_wifi "${ssids[i]}" "${psks[i]}"
done

if [ -n "$root_hash" ]; then
	if valid_hash "$root_hash"; then
		usermod -p "$root_hash" root && log "root password set"
	else
		log "ignoring invalid root password hash"
	fi
fi

[ -n "$user" ] && set_user

if [ ${#keys[@]} -gt 0 ]; then
	authorize_keys root
	[ -n "$user" ] && authorize_keys "$user"
fi

case $permit in yes | no | prohibit-password) sshd_set PermitRootLogin "$permit" ;; esac
case $pwauth in yes | no) sshd_set PasswordAuthentication "$pwauth" ;; esac

exit 0
