#!/usr/bin/env bash
#
# Safe mode: start the game on the plainest graphics configuration there is,
# and keep doing it until somebody says otherwise.
#
# This is the lever the morning of the 31st did not have. The television was
# black; the game was running, playing the music and answering the remote; and
# the only way to try a different graphics configuration was a keyboard carried
# to the machine and an SSH session. With this, the same attempt is a switch on
# a page reachable from a telephone.
#
# **Why it is asked for and not detected.** A game drawing into a mode the panel
# refuses reports nothing wrong. It created its OpenGL context, its main loop is
# beating, its heartbeat is fresh - the watchdog that catches a wedged game
# (watchdog.py) sees a perfectly healthy one. There is no signal on this machine
# that says "the television is black"; the only thing that knows is the person
# looking at it. So this is a switch they throw, not a fault something finds.
#
# **What `on` actually does** is in archstar-fix-game-config, which runs before
# every start of the kiosk: it stops honouring what the machine decided at
# installation and writes `FullScreen=On` and `Screens=1` and nothing else - no
# resolution, so the game asks the panel afresh rather than trusting a memory of
# a panel that may not be the one plugged in.
#
# It is a setting rather than a one-shot on purpose: it has to survive a reboot.
# Somebody with no picture will reboot the machine, and a safe mode that a
# restart forgot would be a safe mode that never got a chance to work.

set -euo pipefail
ARCHSTAR_ACTIONS_LIB="${ARCHSTAR_ACTIONS_LIB:-/usr/lib/archstar-actions/lib/common.sh}"
# shellcheck source=/dev/null
source "${ARCHSTAR_ACTIONS_LIB}"

value="${1:-}"
require_one_of "${value}" on off

remember_setting safe-mode "${value}"

# The setting is read by the pre-start hook, so it only means anything on the
# next start. Restarting here is what makes the switch do something now, which
# is the whole point of a lever somebody throws while looking at a black screen.
if restart_the_game; then
    if [[ "${value}" == 'on' ]]; then
        printf 'the game is restarting on the plainest graphics settings\n'
    else
        printf 'the game is restarting on this machine own settings again\n'
    fi
else
    if [[ "${value}" == 'on' ]]; then
        printf 'safe mode is on; it applies the next time the game starts\n'
    else
        printf 'safe mode is off; the next start uses this machine own settings\n'
    fi
fi
