#!/bin/sh

set -exu

if [ "${container:-}" = "lxc" ]; then
	# podman errors out with:
	# Error: kernel does not support overlay fs: kernel returned unlinkat /home/debci/.local/share/containers/storage/overlay/compat2670129435/merged/subdir: input/output error when we tried to delete an item in the merged directory: driver not supported
	echo "podman cannot run inside lxc" >&2
	exit 77
fi

if [ "$(id -u)" -ne 0 ]; then
	echo "this needs to be run as the superuser" >&2
	exit 1
fi

usage() {
	echo "$0 test-type automation-type" >&2
	echo >&2
	echo " test-type can be one of 'build' or 'installed'" >&2
	echo "   build: test the binary in target/debug/reform-setup" >&2
	echo "   installed: test the reform-setup-wizard package from 'unstable'" >&2
	echo >&2
	echo " automation-type can be one of 'manual' or 'scripted'" >&2
	echo "   manual: start a VNC client for manual testing" >&2
	echo "   scripted: automated clicks and verification" >&2
	echo >&2
	echo "example:" >&2
	echo >&2
	echo "    \$ $0 installed scripted" >&2
	echo "    \$ $0 installed manual" >&2
	echo "    \$ $0 build scripted" >&2
	echo "    \$ $0 build manual" >&2
	echo >&2
	echo "To force a re-build of the underlying system image, rm either" >&2
	echo "swayvnc-installed.tar or swayvnc-build.tar, depending on the test type." >&2
}

if [ "$#" -ne 2 ]; then
	usage
	exit 1
fi
TESTTYPE="$1"
AUTOMATIONTYPE="$2"

case "$AUTOMATIONTYPE" in
	manual|scripted) : ;;
	*)
		echo "invalid automation-type -- can be either 'manual' or 'scripted'" >&2
		echo >&2
		usage
		exit 1
		;;
esac

if [ ! -e "swayvnc-$TESTTYPE.tar" ]; then
	case "$TESTTYPE" in
		installed) set -- --include=reform-setup-wizard ;;
		build)
			set -- \
				--customize-hook='mkdir "$1"/usr/share/reform-setup-wizard/cleanup.d/' \
				--customize-hook='copy-in cleanup.sh /usr/share/reform-setup-wizard/cleanup.d/' \
				--customize-hook='! test -e /usr/bin/reform-setup' \
				--customize-hook='upload ./target/debug/reform-setup /usr/bin/reform-setup' \
				--customize-hook='mkdir "$1"/usr/share/reform-setup-wizard/' \
				--customize-hook='copy-in reform-setup-sway-config /usr/share/reform-setup-wizard/'
			;;
		*)
			echo "invalid test-type -- can be either 'build' or 'installed'" >&2
			echo >&2
			usage
			exit 1
			;;
	esac

	cat << 'END' > swayvnc.sh
#!/bin/sh
set -eux
systemd-machine-id-setup
dbus-daemon --fork --session --print-address=3 --print-pid=4 \
    3> /tmp/dbus-session-bus-address 4> /tmp/dbus-session-bus-pid
DBUS_SESSION_BUS_ADDRESS="$(cat /tmp/dbus-session-bus-address)"
exec env \
	--chdir=/root \
	DBUS_SESSION_BUS_ADDRESS="$DBUS_SESSION_BUS_ADDRESS" \
	SWAYSOCK=/tmp/sway-ipc.sock \
	WLR_LIBINPUT_NO_DEVICES=1 \
	WLR_BACKENDS=headless \
	WLR_RENDERER=pixman \
	WLR_RENDERER_ALLOW_SOFTWARE=1 \
	XDG_RUNTIME_DIR=/tmp \
	CHROOT_MODE=1 \
	sway --config /usr/share/reform-setup-wizard/reform-setup-sway-config
END
	chmod +x swayvnc.sh

	cat << 'END' > wayvnc.conf
address=0.0.0.0
enable_auth=false
username=root
password=rootme
private_key_file=/root/key.pem
certificate_file=/root/cert.pem
END

	mmdebstrap \
		--include=python3,python3-gi,sway,wayvnc,socat,dbus-daemon,libglib2.0-bin,libgdk-pixbuf2.0-bin,gsettings-desktop-schemas,gnome-settings-daemon,librsvg2-common,libopengl0,grim,gir1.2-gdkpixbuf-2.0 \
		--customize-hook='copy-in swayvnc.sh /' \
		--customize-hook='mkdir -p "$1"/root/.config/wayvnc "$1"/root/.config/dconf' \
		--customize-hook='echo "exec wayvnc 0.0.0.0 5910" > "$1"/etc/sway/config.d/wayvnc.conf' \
		--customize-hook='echo "exec \"socat TCP-LISTEN:7023,fork UNIX-CONNECT:/tmp/sway-ipc.sock\"" > "$1"/etc/sway/config.d/socat.conf' \
		--customize-hook='echo "output HEADLESS-1 resolution 1920x1080" > "$1"/etc/sway/config.d/headless.conf' \
		--customize-hook='upload wayvnc.conf /root/.config/wayvnc/config' \
		--customize-hook='mkdir -p "$1"/etc/skel/.config/' \
		--customize-hook='touch "$1"/etc/skel/.config/wayfire.ini' \
		--customize-hook='openssl req -x509 -newkey rsa:4096 -sha256 -days 3650 -nodes -keyout "$1"/root/key.pem -out "$1"/root/cert.pem -subj /CN=localhost -addext subjectAltName=DNS:localhost,DNS:localhost,IP:127.0.0.1' \
		"$@" \
		unstable "swayvnc-$TESTTYPE.tar"

	rm wayvnc.conf swayvnc.sh
fi

podman rmi -f swayvnc
podman import "swayvnc-$TESTTYPE.tar" swayvnc

set --
# disable cgroups when run inside docker as otherwise podman errors out with
# Error: OCI runtime error: crun: the requested cgroup controller `pids` is not available
if grep --quiet /docker/ /proc/self/mountinfo; then
	set -- --cgroups=disabled
fi

rm -f mycid
setpriv --pdeathsig TERM podman run --cidfile=mycid --cap-add SYS_ADMIN --uts=private "$@" -p127.0.0.1:5910:5910 -p127.0.0.1:7023:7023 swayvnc /swayvnc.sh &
PODMANPID=$!

case "$AUTOMATIONTYPE" in
	scripted)
		mkdir -p screenshots
		trap 'cp -a screenshots "$AUTOPKGTEST_ARTIFACTS"' EXIT INT TERM
		cat << END | python3 minivncdotool.py
connect 127.0.0.1 5910 60
sleep 60
capture screenshots/00test.png
wait_visible patterns/get_started.png 60
mousemove patterns/get_started.png
capture screenshots/00welcome.png
click
wait_visible patterns/keyboard_layout.png 8
mousemove 0 0
mousemove patterns/next.png
capture screenshots/01keyboard.png
click
wait_visible patterns/time.png 8
mousemove 0 0
mousemove patterns/next.png
capture screenshots/02time.png
click
wait_visible patterns/desktop.png 8
mousemove 0 0
mousemove patterns/next.png
capture screenshots/03desktop.png
click
wait_visible patterns/root.png 8
key p
sleep 1
key Tab
sleep 1
key p
mousemove 0 0
mousemove patterns/next.png
capture screenshots/04root.png
click
wait_visible patterns/computer_name.png 8
key m
sleep 1
key m
mousemove 0 0
mousemove patterns/next.png
capture screenshots/05hostname.png
click
wait_visible patterns/account.png 8
key u
sleep 1
key Tab
sleep 1
key p
sleep 1
key Tab
sleep 1
key p
mousemove 0 0
mousemove patterns/next.png
capture screenshots/06account.png
click
END

		wait $PODMANPID

		podman start "$(cat mycid)"
		podman exec -i "$(cat mycid)" sh <<'END'
set -exu
test -s /etc/machine-id
test "$(readlink /etc/localtime)" = "/usr/share/zoneinfo/Europe/Berlin"
test "$(cat /etc/timezone)" = "Europe/Berlin"
test "$(tail -1 /etc/passwd)" = "u:x:1000:1000:,,,:/home/u:/bin/bash"
test "$(tail -1 /etc/group)" = "u:x:1000:"
grep --quiet --fixed-strings --line-regexp 'command = "/usr/bin/tuigreet --window-padding 4 --remember --asterisks --cmd /usr/bin/wayfire"' /etc/greetd/config.toml
cmp /home/u/.config/sway/config.d/input /etc/skel/.config/sway/config.d/input
cat <<'KEYBOARD' | cmp /etc/default/keyboard
# KEYBOARD CONFIGURATION FILE

# Consult the keyboard(5) manual page.

XKBMODEL="pc105"
XKBLAYOUT="eu"
XKBVARIANT=""
XKBOPTIONS=""

BACKSPACE="guess"
KEYBOARD
cat <<'KEYBOARD' | cmp /etc/skel/.config/sway/config.d/input
# change to de if you have a QWERTZ keyboard, for example
input * {
        xkb_layout eu
        xkb_variant ""
        xkb_options lv3:ralt_switch
}
KEYBOARD
END
		podman stop "$(cat mycid)"
	;;
	'manual')
		cat << END | python3 minivncdotool.py
connect 127.0.0.1 5910 30
wait_visible patterns/get_started.png 30
END
		vinagre 127.0.0.1::5910
		;;
esac

podman rmi -f swayvnc
# podman rmi seems to delete the cidfile
rm -f mycid
