#!/usr/bin/env bash
# talking-heads: web page kiosk on boot.

set -e

LIB=/usr/local/lib/talking-heads
CONFIG=/etc/talking-heads/config

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

usage() {
    cat <<EOF
Usage: talking-heads <command>

  kiosk      switch to kiosk mode
  desktop    switch to desktop mode
  toggle     switch to the other mode
  status     show the current mode and settings
  config     edit the settings, then apply them
  restart    restart the kiosk
  logs       show the kiosk logs since boot (journalctl options allowed, e.g. -f)
  setup      prepare the kiosk after install or upgrade
  browser    open the page fullscreen (run by the kiosk service)
EOF
}

need_root() {
    if [[ $EUID -ne 0 ]]; then
        echo "Run as root: sudo talking-heads $command" >&2
        exit 1
    fi
}

command="${1:-help}"
shift || true

case "$command" in
    kiosk | desktop | toggle)
        need_root
        exec "$LIB/mode" "$command"
        ;;
    status)
        exec "$LIB/mode" status
        ;;
    config)
        need_root
        "${EDITOR:-nano}" "$CONFIG"
        exec "$LIB/setup"
        ;;
    restart)
        need_root
        systemctl restart "$UNIT"
        ;;
    logs)
        exec journalctl -u "$UNIT" -b "$@"
        ;;
    setup)
        need_root
        exec "$LIB/setup"
        ;;
    browser)
        exec "$LIB/browser"
        ;;
    help | -h | --help)
        usage
        ;;
    *)
        usage >&2
        exit 1
        ;;
esac
