#!/bin/bash

trap "exit" INT TERM
trap "kill 0" EXIT

kill_descendant_processes() {
    local pid="$1"
    local and_self="${2:-false}"
    if children="$(pgrep -P "$pid")"; then
        for child in $children; do
            kill_descendant_processes "$child" true
        done
    fi
    if [[ "$and_self" == true ]]; then
        kill -9 "$pid"
    fi
}

# # Run Auto-Push in Background
# ./auto-push.sh &
# AUTO_PUSH_PID=$!

# Run paper build
pushd paper/doc 2>&1 > /dev/null
./build.sh watch &
PAPER_BUILD_PID=$!
popd 2>&1 > /dev/null

if ! [[ "$1" == "--no-server" ]]; then
    # Run background server
    pushd server/Dacryptero 2>&1 > /dev/null
    dotnet watch run --no-host --db-key dDZ2OXkkQiZFKUhATWNRZlRqV25acjR1N3gheiVDKkY= &
    BACKGROUND_SERVER_PID=$!
    popd 2>&1 > /dev/null
fi

# Run Elm Live for ui preview
pushd ui 2>&1 > /dev/null
./elm-live.sh &
ELM_LIVE_PID=$!
popd 2>&1 > /dev/null

# ask for the elm live restart
while true; do

    sleep 1s
    read -n 1 -s -p "Press any key to restart elm live"
    kill_descendant_processes $ELM_LIVE_PID
    kill -s 9 -- $ELM_LIVE_PID || echo "Elm live (PID: $ELM_LIVE_PID) not found"
    sleep 1s

    # restart Elm Live for ui preview
    pushd ui 2>&1 > /dev/null
    ./elm-live.sh &
    ELM_LIVE_PID=$!
    popd 2>&1 > /dev/null

done

wait