#!/usr/bin/env bash
###
# File: sunshine-run
# Project: bin
# File Created: Tuesday, 23rd August 2023 3:28:52 pm
# Author: Josh.5 (jsunnex@gmail.com)
# -----
# Last Modified: Friday, 23rd August 2023 4:21:00 pm
# Modified By: Josh.5 (jsunnex@gmail.com)
###
set -e

exec >> >(tee -a /tmp/sunshine-exec-run.log) 2>&1
echo
echo "-------------------------------"
echo
date
echo
echo "-------------------------------"
echo
echo "**** Execute sunshine-run ****"
echo

# Trap SIGINT, SIGQUIT, SIGHUP, SIGTERM to forward signals to the child process
_term() {
    if [ -n "${proc_pid}" ]; then
        echo "  - Forwarding signal $1 to process ${proc_pid}"
        kill -s "${1}" "${proc_pid}"
    fi
}
trap '_term INT' SIGINT
trap '_term QUIT' SIGQUIT
trap '_term HUP' SIGHUP
trap '_term TERM' SIGTERM

# Run child process
/usr/bin/dumb-init "${@}" &
proc_pid=$!
echo "  - Recording sunshine-run PID '${proc_pid}' in /tmp/sunshine-exec-run.pid"
echo "${proc_pid}" > /tmp/sunshine-exec-run.pid

# Wait for child process to exit:
echo "  - Waiting for PID '${proc_pid}' to exit"
wait "$proc_pid"

# Clean up PID file
rm -f /tmp/sunshine-exec-run.pid

echo "DONE"
