#!/bin/sh
# deckos - small helper that comes with the Deck OS package.
#   deckos open          open Deck OS in your web browser (the apps-menu launcher runs this)
#   deckos status        is it running, and where to open it
#   deckos setup-code    the one-time code for finishing setup from a phone or another computer
#   deckos logs          what Deck OS has been doing
#   deckos mode user     run Deck OS as you (data in ~/.local/share/deckos/data) instead of system-wide
#   deckos mode system   back to the system-wide service (data in /var/lib/deckos) - the default
#   deckos version
set -u
user_mode() { systemctl --user is-enabled --quiet deckos.service 2>/dev/null; }
env_file() { if user_mode; then echo "${XDG_CONFIG_HOME:-$HOME/.config}/deckos/deckos.env"; else echo /etc/deckos/deckos.env; fi; }
port() {
  p=$(sed -n 's/^[[:space:]]*DECKOS_PORT=\([0-9][0-9]*\).*/\1/p' "$(env_file)" 2>/dev/null | tail -n 1)
  echo "${p:-8765}"
}
up() { python3 - "$1" <<'PY' 2>/dev/null
import sys, urllib.request
try:
    urllib.request.urlopen(f"http://127.0.0.1:{sys.argv[1]}/setup", timeout=2)
except urllib.error.HTTPError:
    pass
PY
}
say() { printf '%s\n' "$*"; command -v notify-send >/dev/null && [ -n "${DISPLAY:-}${WAYLAND_DISPLAY:-}" ] && notify-send -i deckos "Deck OS" "$*" 2>/dev/null; return 0; }

cmd="${1:-open}"
case "$cmd" in
  open)
    P=$(port); URL="http://localhost:$P"
    if ! up "$P"; then
      i=0; while [ $i -lt 20 ] && ! up "$P"; do i=$((i + 1)); sleep 1; done
      up "$P" || say "Deck OS isn't answering yet. It may still be starting - give it a minute. If it stays this way: deckos status"
    fi
    if command -v xdg-open >/dev/null; then xdg-open "$URL" >/dev/null 2>&1 &
    else echo "Open this in your web browser: $URL"; fi ;;
  status)
    P=$(port)
    if user_mode; then echo "Mode: your account (data in ${XDG_DATA_HOME:-$HOME/.local/share}/deckos/data)"; systemctl --user --no-pager status deckos.service | sed -n '1,3p'
    else echo "Mode: system-wide (data in /var/lib/deckos)"; systemctl --no-pager status deckos.service 2>/dev/null | sed -n '1,3p'; fi
    if up "$P"; then echo "Running. Open http://localhost:$P on this computer."
      ip=$(hostname -I 2>/dev/null | awk '{print $1}'); [ -n "$ip" ] && echo "Phones and tablets on your Wi-Fi: http://$ip:$P"
    else echo "Not answering on port $P right now. See: deckos logs"; fi ;;
  setup-code)
    if user_mode; then f="${XDG_DATA_HOME:-$HOME/.local/share}/deckos/data/setup-code.txt"; c=$(cat "$f" 2>/dev/null)
    else c=$(sudo cat /var/lib/deckos/setup-code.txt 2>/dev/null); fi
    if [ -n "$c" ]; then echo "Your one-time setup code: $c"
    else echo "No setup code right now: setup is already finished, or Deck OS hasn't started yet. On this computer you don't need one - just open http://localhost:$(port)/setup"; fi ;;
  logs)
    if user_mode; then journalctl --user -u deckos -n 100 --no-pager; else journalctl -u deckos -n 100 --no-pager; fi ;;
  mode)
    case "${2:-}" in
      user)
        echo "Switching Deck OS to run as $(id -un). It asks for your password once to turn off the system-wide copy."
        sudo sh -c 'touch /etc/deckos/user-mode && systemctl disable --now deckos.service' || exit 1
        systemctl --user daemon-reload; systemctl --user enable --now deckos.service || exit 1
        echo "Done. Your data: ${XDG_DATA_HOME:-$HOME/.local/share}/deckos/data"
        echo "To keep it running while you're logged out:   loginctl enable-linger $(id -un)" ;;
      system)
        systemctl --user disable --now deckos.service 2>/dev/null
        sudo sh -c 'rm -f /etc/deckos/user-mode && systemctl enable --now deckos.service' || exit 1
        echo "Done. Deck OS runs system-wide again (data in /var/lib/deckos)." ;;
      *) echo "Use:  deckos mode user   or   deckos mode system"; exit 2 ;;
    esac
    echo "Each mode keeps its own data; switching doesn't copy or delete anything." ;;
  version) python3 -c "import re;print(re.search(r'^VERSION = \"([^\"]+)\"', open('/opt/deckos/app/product.py').read(), re.M).group(1))" ;;
  -h|--help|help) sed -n '2,10p' "$0" | sed 's/^# \{0,1\}//' ;;
  *) echo "Unknown command: $cmd   (try: deckos help)"; exit 2 ;;
esac
