#!/bin/sh -e

un="${1:-sodface}"

if [ ! -d /home/${un} ]
then
	echo "Adding user ${un}"
	adduser ${un}
	addgroup ${un} audio
	addgroup ${un} input
	addgroup ${un} netdev
	addgroup ${un} video
	addgroup ${un} wheel
fi


if ! grep -q sodface.com /etc/apk/repositories
then
	echo "http://www.sodface.com/repo" >> /etc/apk/repositories
	echo "http://10.0.0.10/repo" >> /etc/apk/repositories
	wget -O - http://www.sodface.com/repo/sodface-pub-key.tar.gz \
		| tar xzvf - -C /etc/apk/keys
	apk update
fi

if [ ! -x /usr/bin/herbstluftwm ]
then
	apks="
		adwaita-icon-theme
		font-opensans
		herbstluftwm
		mesa-dri-gallium
		mesa-egl
		mesa-utils
		ttf-dejavu
		"
	setup-xorg-base ${apks}

	apks="
		alsa-utils
		alsa-ucm-conf
		brightnessctl
		dbus
		dmenu
		doas
		feh
		firefox
		intel-media-driver
		iwd
		mpv
		nfs-utils
		openresolv
		pciutils-libs
		pipewire
		pipewire-alsa
		pipewire-tools
		pm-utils
		rng-tools
		sakura
		util-linux-misc
		wireplumber
		xrandr
		"
	apk add ${apks}

	echo "permit persist :wheel" >> /etc/doas.d/doas.conf
	ln -s /usr/bin/herbstclient /usr/bin/hc

	rc-update add alsa
	rc-update add dbus
	rc-update add iwd
	rc-update add rngd boot
	rc-update del networking boot

	sed -in 's/^#\[General\]/\[General\]/' /etc/iwd/main.conf
	sed -in 's/^#EnableNetworkConfiguration/EnableNetworkConfiguration/' /etc/iwd/main.conf
	sed -in 's/^#\[Network\]/\[Network\]/' /etc/iwd/main.conf
	sed -in 's/^#NameResolvingService/NameResolvingService/' /etc/iwd/main.conf
fi

tmp=$(mktemp -td cb.XXXXXX)
wget -O - http://www.sodface.com/repo/hp/sodco/setup-gui.tar.gz \
	| tar xzvf - -C ${tmp}

install -Dm 755 ${tmp}/files/30-touchpad.conf -t /etc/X11/xorg.conf.d
install -Dm 755 ${tmp}/files/autostart -t /home/${un}/.config/herbstluftwm
install -Dm 644 ${tmp}/files/dot-profile /home/${un}/.profile
install -Dm 644 ${tmp}/files/dot-xinitrc /home/${un}/.xinitrc
install -Dm 644 ${tmp}/files/dot-xserverrc /home/${un}/.xserverrc
install -Dm 644 ${tmp}/wallpaper/* -t /home/${un}/.config/wallpaper
chown -R ${un}:${un} /home/${un}

rm -rf ${tmp}

echo "Done, please reboot."