#!/bin/bash
set -uo pipefail

# Closes Chrome properly before the machine goes down.
#
# Chrome marks a profile as crashed when it does not get to run its own
# shutdown, which is what produces "Restore pages? Chrome didn't shut
# down correctly" on the next boot. The browser process handles SIGTERM
# by shutting down cleanly, so it is worth giving it one and waiting a
# moment before the session is torn out from under it.
#
# --hide-crash-restore-bubble already hides the prompt. This stops the
# profile being marked crashed at all, which is the tidier half of the
# same problem.
#
# Run from ekklesia-classroom-shutdown.service. Never fails: a shutdown
# that will not finish is far worse than a crash flag.

CLASSROOM_USER=classroom
WAIT_SECONDS=8

log() {
    echo "[classroom-shutdown] $1"
}

browser_processes() {
    # Only the browser process, not its renderers: those carry --type=
    # and are Chrome's own business to reap.
    local pid
    for pid in $(pgrep -u "$CLASSROOM_USER" -x chrome 2>/dev/null); do
        # Braces so a process exiting between pgrep and this read is
        # silent: bash reports a failed redirection itself, before the
        # command's own stderr redirect can catch it.
        if ! { tr '\0' '\n' < "/proc/$pid/cmdline"; } 2>/dev/null |
                grep -q '^--type='; then
            echo "$pid"
        fi
    done
}

pids="$(browser_processes)"

if [[ -z "$pids" ]]; then
    exit 0
fi

log "asking Chrome to close"

# shellcheck disable=SC2086
kill -TERM $pids 2>/dev/null || true

for _ in $(seq 1 $((WAIT_SECONDS * 5))); do
    if [[ -z "$(browser_processes)" ]]; then
        log "Chrome closed cleanly"
        exit 0
    fi
    sleep 0.2
done

log "Chrome did not close in time; leaving it to systemd"
exit 0
