#!/usr/bin/bash

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

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

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 &

cmd=$1
shift
"$cmd" "$@"

if [[ "${terminateImmediately}" = "true" ]]; then
	echo "Immediately terminating sandbox per config"
	stopApp
	echo terminate-now >/run/startSignal
	exit 0
fi

_procCnt=$(ps | grep -v zenity | grep -v glycin | grep -v prlimit | grep -v grep | wc -l)
#ps | grep -v zenity | grep -v glycin | grep -v grep
echo "Process count: ${_procCnt}"
if [[ "${_procCnt}" -gt 7 ]]; then
	#sleep 1s
	_procCnt=$(ps | grep -v zenity | grep -v glycin | grep -v prlimit | grep -v grep | wc -l)
	#ps | grep -v zenity | grep -v glycin | grep -v prlimit | grep -v grep
	echo "Process count: ${_procCnt}"
fi
if [[ "${_procCnt}" -le 7 ]]; 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
		_procCnt=$(ps | grep -v zenity | wc -l)
		#echo "Process count: ${_procCnt}"
		if [[ "${_procCnt}" -le 9 ]]; then
			echo "Terminating sandbox..."
			stopApp
			break
		fi
	done
fi
