#!/bin/sh
# Armbian: system setup that upstream does at install time
# (install/config/firewall.sh, install/config/snapper.sh,
# install/config/lockscreen-pam.sh,
# install/config/enable-services.sh). Each part
# runs once. armbian-hyprland-shell-setup.service starts it at boot.
set -e
state=/var/lib/armbian-hyprland-shell
mkdir -p "$state"

# Lock screen PAM, as upstream (install/config/lockscreen-pam.sh).
# Without /etc/pam.d/omarchy-lock-password the shell never locks.
# First, so that a failure of a later step cannot block it.
# Keep an existing file: an admin can have changed it. Fingerprint setup
# also writes it, so a missing file means no fingerprint setup to keep.
if [ ! -e "$state/lock-done" ]; then
	if [ ! -e /etc/pam.d/omarchy-lock-password ]; then
		OMARCHY_PATH=/usr/share/omarchy /usr/share/omarchy/bin/omarchy-apply-lock
	fi
	touch "$state/lock-done"
fi

# Firewall, as upstream. Keep the rules of an admin who already enabled ufw.
if [ ! -e "$state/firewall-done" ] && command -v ufw >/dev/null; then
	if grep -q '^ENABLED=yes' /etc/ufw/ufw.conf; then
		touch "$state/firewall-done"
	# ufw-docker install needs the docker command (package docker-cli, which
	# docker.io only recommends). Without it, wait for a later boot, not fail.
	elif command -v ufw-docker >/dev/null && command -v docker >/dev/null; then
		# Armbian images enable SSH: keep it reachable.
		ufw allow 22/tcp comment 'ssh' >/dev/null
		# -e: a failed rule install, such as ufw-docker, stops the setup.
		# Then firewall-done is not written and the next boot tries again.
		bash -e /usr/share/omarchy/install/config/firewall.sh
		ufw --force enable
		touch "$state/firewall-done"
	fi
fi

# Docker starts on first use, as upstream: the socket, not the daemon at boot.
if [ ! -e "$state/docker-done" ] && [ -e /usr/lib/systemd/system/docker.socket ]; then
	systemctl disable docker.service
	systemctl enable docker.socket
	touch "$state/docker-done"
fi

# Snapshots, as upstream: a snapper config for a btrfs root. omarchy-update
# takes a snapshot before it updates. Upstream runs this on a new install
# only: keep a root config that an admin made before.
if [ ! -e "$state/snapper-done" ] && command -v snapper >/dev/null && [ "$(findmnt -n -o FSTYPE /)" = btrfs ]; then
	if [ ! -e /etc/snapper/configs/root ]; then
		bash -e /usr/share/omarchy/install/config/snapper.sh
	fi
	touch "$state/snapper-done"
fi
