#!/bin/bash
set -e
cd "$(dirname "$0")/_install"

PACKAGES=(
	
	# system
	linux base linux-firmware lvm2 sudo polkit # base
	pulseaudio pulseaudio-bluetooth bluez bluez-utils networkmanager udisks2 # system
	openssh man-db restic htop # admin utils

	# generic runtime
	nodejs dash

	# cli programs
	vifm vim # navigation & editors 
	shellcheck # shell scripting
	hugo miniserve neomutt translate-shell # www
	gnupg pass pass-otp # crypt
	jq libqalculate imagemagick # data processing
	git zip # others
	
	# desktop env
	greetd wlr-randr sway swaybg swayidle # basic
	foot bemenu-wayland i3blocks mako libnotify # terminals, ui
	wev wl-clipboard wtype slurp grim # interaction
	ttf-roboto ttf-roboto-mono ttf-font-awesome # fonts

	# gui apps
	imv mpv gimp # media
	qutebrowser qt6-wayland # www
	sqlitebrowser qt5-wayland # db

	# extensions 
	vim-ale vim-fugitive

	# not so good
	telegram-desktop libreoffice-still 

)

install() {
	pacman -S --needed --noconfirm "$@"
}
file_has_line() {
	grep -qxF "$2" "$1" || echo "$2" >> "$1"
}
cp_chown() {
	cp -rf "$1" "$2"
	chown "$3" "$2" -R
	chmod "$4" "$2" -R
}

[ "$(id -u)" != "0" ] && echo "ERROR: root required" >&2 && exit 1

pacman -Syu --noconfirm
install "${PACKAGES[@]}"

file_has_line "/etc/profile" "umask 002"
find /etc/pam.d -type f -exec sed -i -e 's/^session optional pam_umask.so$/session optional pam_umask.so usergroups/g' {} \;

sed -i 's/#AutoEnable=true/AutoEnable=false/' /etc/bluetooth/main.conf
systemctl enable bluetooth --now

while read -r entity; do
	# group <name> <id>
	# user <name> <id> [<secondary groups>...]
	read -ra entity_parts <<< "$entity"
	etype="${entity_parts[0]}"
	ename="${entity_parts[1]}"
	eid="${entity_parts[2]}"
	[ "$etype" != "user" ] && [ "$etype" != "group" ] && echo "ERROR: bad entity type" >&2 && exit 1

	# every user has their own primary group with id matching uid,
	# so for each entry we need a usergroup
	if [ -z "$(getent group "$eid")" ]; then
		echo "Creating group \"$ename\", id=$eid"
		groupadd --gid "$eid" "$ename"
	fi
	if [ "$etype" = "user" ]; then
		if ! id "$eid" >/dev/null 2>&1; then
			echo "Creating user \"$ename\", id=$eid"	
			useradd --gid "$eid" --uid "$eid" -m "$ename"
		fi
		usermod -aG "$(IFS=,; echo "${entity_parts[*]:3}")" "$ename"
	else # group
		if [[ "$ename" == share-* ]]; then
			echo "Creating shared dir $ename"
			mkdir -p "/home/$ename"
			chgrp "$ename" -R "/home/$ename"
			chmod u=rwX,g=rwX,o= -R "/home/$ename"
			find "/home/$ename" -type d -print0 | xargs -0 chmod g+s

		fi
	fi
done </root/users.conf

cp_chown greetd.toml /etc/greetd/config.toml root:root 644

custom_script="./custom/$(cat /etc/hostname).sh"
if [ -f "$custom_script" ]; then
	echo "Executing host-specific $custom_script"
	# shellcheck disable=SC1090
	source "$custom_script"
fi