#!/usr/bin/env bash
# Switches between kiosk and desktop mode, or shows the current one.
# Run by talking-heads kiosk|desktop|toggle|status.
#
# Kiosk mode:
#   - talking-heads@<KIOSK_TTY> starts on boot
#   - the display manager is stopped, unless KIOSK_KEEP_DESKTOP=yes keeps it
#     on its own console (Ctrl+Alt+F<n> to switch)
#   - the machine stays on when the lid is closed (harmless on desktops)
#
# Desktop mode:
#   - kiosk stopped, display manager and default target restored
#   - default lid behaviour

set -e

CONFIG=/etc/talking-heads/config
LOGIND_CONF=/etc/systemd/logind.conf.d/talking-heads.conf

[[ -f "$CONFIG" ]] && source "$CONFIG"
UNIT="talking-heads@${KIOSK_TTY:-tty8}.service"
DM="${DESKTOP_DISPLAY_MANAGER:-}"

status() {
    echo "Kiosk          : $(systemctl is-enabled "$UNIT" 2>/dev/null || true), $(systemctl is-active "$UNIT" || true) ($UNIT)"
    echo "URL            : ${KIOSK_URL:-not set}"
    [[ -z "$DM" ]] || echo "Display manager: $(systemctl is-enabled "$DM" 2>/dev/null || true), $(systemctl is-active "$DM" || true) ($DM)"
    echo "Default target : $(systemctl get-default)"
    echo "Lid switch     : $([[ -f "$LOGIND_CONF" ]] && echo ignored || echo default)"
}

reload_logind() {
    systemctl reload systemd-logind || echo "Lid setting applies after a reboot."
}

# Switches now, after the persistent changes. Jobs are queued without
# waiting, since stopping the display manager may end the session running
# this script.
switch_now() {
    local stop=$1 start=$2
    [[ -z "$stop" ]] || systemctl --no-block stop "$stop"
    [[ -z "$start" ]] || systemctl --no-block start "$start"
}

kiosk_mode() {
    mkdir -p "$(dirname "$LOGIND_CONF")"
    cat >"$LOGIND_CONF" <<'EOF'
# Kiosk mode (talking-heads): stay on when the lid is closed,
# on battery or AC power.
[Login]
HandleLidSwitch=ignore
HandleLidSwitchExternalPower=ignore
EOF
    reload_logind

    systemctl set-default graphical.target
    systemctl enable "$UNIT"
    if [[ "${KIOSK_KEEP_DESKTOP:-no}" == "yes" ]]; then
        # Desktop first: the kiosk takes the screen when it starts.
        [[ -z "$DM" ]] || systemctl enable --now "$DM"
        switch_now "" "$UNIT"
    else
        [[ -z "$DM" ]] || systemctl disable "$DM" || true
        switch_now "$DM" "$UNIT"
    fi
    echo "KIOSK mode enabled."
}

desktop_mode() {
    rm -f "$LOGIND_CONF"
    reload_logind

    systemctl disable "$UNIT"
    [[ -z "${DESKTOP_TARGET:-}" ]] || systemctl set-default "$DESKTOP_TARGET"
    [[ -z "$DM" ]] || systemctl enable "$DM"
    switch_now "$UNIT" "$DM"
    echo "DESKTOP mode enabled."
}

case "${1:-}" in
    kiosk) kiosk_mode ;;
    desktop) desktop_mode ;;
    toggle)
        if systemctl is-enabled --quiet "$UNIT"; then desktop_mode; else kiosk_mode; fi
        ;;
    status) ;;
    *)
        echo "Usage: talking-heads kiosk|desktop|toggle|status" >&2
        exit 1
        ;;
esac

[[ "${1:-}" == "status" ]] || echo ""
status
