#!/bin/sh

[[ -r /usr/lib/garuda-tools/util-live.sh ]] && source /usr/lib/garuda-tools/util-live.sh

DRIVER="$(kernel_cmdline driver nonfree)"

REPO_PATH='/opt/ght'
PAC_CONF="${REPO_PATH}/pacman-ght.conf"

# In a live session we should never have a database lock at boot, this is a bug!
# In the past pamac caused issues about that.
# Fixed here: https://github.com/manjaro/manjaro-tools/commit/57a039088ae4485bc5dc411e36a90c0753e670f1
seconds="0"
while [ -e "/var/lib/pacman/db.lck" ]; do
	echo 'Pacman is not ready yet. Will try again in 10 seconds.' >>/var/log/ght-live.log
	echo '----' >>/var/log/ght-live.log
	ps -ef >>/var/log/ght-live.log
	echo '----' >>/var/log/ght-live.log
	seconds=$(($seconds + 10))
	sleep 10
	if [[ "$seconds" == "30" ]]; then
		echo 'Warning: removing pacman db.lck!' >>/var/log/ght-live.log
		rm /var/lib/pacman/db.lck
	fi
done

# hwdetect_graphics
if [[ -e "${PAC_CONF}" ]]; then
	MODULES_DIR='/etc/calamares/modules'
	echo "Running Garuda Hardware Tool..." >>/var/log/ght-live.log
	sed -e "s|^.*driver:.*|driver: ${DRIVER}|" -i "${MODULES_DIR}/ghtcfg.conf"
	DRIVER_PARAM="--free"
	if [[ "${DRIVER}" == "nonfree" ]]; then
		DRIVER_PARAM="--nonfree"
	fi
	garuda-hardware-tool --sync --noconfirm ${DRIVER_PARAM} --pacmanconfig "${PAC_CONF}" >>/var/log/ght-live.log 2>&1
	systemctl --no-block start ght-live.target
	echo "Garuda Hardware Tool DONE" >>/var/log/ght-live.log
fi
