#!/usr/bin/bash
# shellcheck disable=SC2154,SC2155,SC2009

function startLoop() {
	systemd-notify --ready --status="Sandbox startup complete" & 2>/dev/null
	while true; do
		inotifywait \
			-e modify \
			--quiet \
			/run/startSignal 1>/dev/null
		if [[ $? -eq 1 ]]; then
			stopApp
		fi
		local _launch="$(cat /run/startSignal 2>/dev/null)"
		if [[ ${_launch} =~ terminate ]]; then
			break
		elif [[ ${_launch} = finish ]]; then
			continue
		else
			echo "Starting auxiliary application"
			# shellcheck disable=SC2046
			eval $(${_launch}) &
			systemd-notify --ready 2>/dev/null
			systemd-notify --status="Started auxiliary Application" 2>/dev/null
		fi
	done
}

function calcProcCnt() {
	_procCnt=$(ps | grep -vE 'ps|helper|zenity|glycin|grep|inotifywait|prlimit' -c)
	echo "Calculated process: $(ps | grep -vE 'ps|helper|zenity|glycin|grep|inotifywait|prlimit')"
}

function stopApp() {
	echo "terminate-now" >/run/startSignal
}

function askStop() {
	if [[ "${LANG}" =~ "zh_CN" ]]; then
		/usr/bin/zenity \
			--title "${friendlyName}" \
			--icon=background-app-ghost-symbolic \
			--question \
			--text="主程序已退出但有残余进程, 停止沙盒?"
	else
		/usr/bin/zenity \
			--title "${friendlyName}" \
			--icon=background-app-ghost-symbolic \
			--question \
			--text="Main process terminated with leftovers, stop sandbox?"
	fi
	if [[ $? -eq 0 ]]; then
		systemd-notify --stopping
		echo "User opted to kill processes"
		stopApp
	else
		systemd-notify --status="User denied session termination"
	fi
}

startLoop &

if [[ "${_portableDebug}" -eq 1 ]]; then
	bash --noprofile --rcfile /run/bashrc
elif [[ "${_portableBusActivate}" -eq 1 ]]; then
	if [[ -n "${busLaunchTarget}" ]]; then
		${busLaunchTarget} ${targetArgs}
	else
		echo "Warning: busLaunchTarget not defined"
		${launchTarget} ${targetArgs}
	fi
else
	${launchTarget} ${targetArgs}
fi

if [[ "${terminateImmediately}" = "true" ]]; then
	echo "Immediately terminating sandbox per config"
	stopApp
	exit 0
fi

calcProcCnt
if [[ "${_procCnt}" -gt 1 ]]; then
	calcProcCnt
	echo "Process count: ${_procCnt}"
fi
if [[ "${_procCnt}" -le 1 ]]; then
	echo "No more application running, terminating..."
	#kill %1
	echo terminate-now >/run/startSignal
	exit 0
else
	echo "Warning! There're still processes running in the background."
	systemd-notify --status="Main application exited"
	echo "Staying in background until all process terminates"
	askStop &
	while true; do
		sleep 5s
		calcProcCnt
		if [[ "${_procCnt}" -le 1 ]]; then
			echo "Terminating sandbox..."
			stopApp
			break
		fi
	done
fi
