#!/usr/bin/env bash
#
# The desk-side half: generate this dock's files and put them where OpenDeck and
# systemd will find them. Run it ON THE DESKTOP THE DOCK IS PLUGGED INTO, from a
# checkout of this repo.
#
#     stream-dock/setup-stream-dock.sh
#
# What it does:
#   1. runs generate.py against CoreSystemConfig.json
#   2. installs the starting leds.toml for the akp05 device plugin (backing up yours)
#   3. installs led-sync.env (mode 0600 — it holds the HA token) and the systemd
#      --user unit for the ring-colour service
#   4. tells you what it could not do for you, which is every step that needs a
#      human in front of OpenDeck's own UI
#
# It installs no plugins. Both of them come from third parties as release downloads,
# and a setup script that silently pulls executables off the internet onto a desktop
# is not a trade this project makes — the two links are printed instead. See
# stream-dock/README.md §2.
#
# Options:
#   --no-enable    install the unit but do not start it
#   --config PATH  use a different CoreSystemConfig.json
set -euo pipefail

REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
DOCK_DIR="${REPO_ROOT}/stream-dock"
# shellcheck source=/dev/null
source "${REPO_ROOT}/tools/lib/coreconfig.sh"

ENABLE=true
while [[ $# -gt 0 ]]; do
  case "$1" in
    --no-enable) ENABLE=false; shift ;;
    --config) CORE_CONFIG_PATH="$2"; shift 2 ;;
    *) core_die "unknown option: $1" ;;
  esac
done

core_load
[[ "$CORE_STREAM_DOCK_ENABLED" == "true" ]] || core_die \
  "stream_dock.enabled is false in $(basename "$CORE_CONFIG_PATH") — nothing to set up"

core_log "Generating this dock's files"
"${DOCK_DIR}/generate.py" "$CORE_CONFIG_PATH"
GEN="${DOCK_DIR}/generated"

# --- the device plugin's LED file --------------------------------------------------
LEDS_PATH="${CORE_STREAM_DOCK_LED_CONFIG_PATH:-}"
LEDS_PATH="${LEDS_PATH:-$HOME/.config/opendeck-akp05/leds.toml}"
LEDS_PATH="${LEDS_PATH/#\~/$HOME}"
core_log "Installing starting knob colours -> ${LEDS_PATH}"
mkdir -p "$(dirname "$LEDS_PATH")"
if [[ -f "$LEDS_PATH" ]] && ! grep -q "Generated by stream-dock" "$LEDS_PATH"; then
  cp "$LEDS_PATH" "${LEDS_PATH}.bak-streamdock"
  core_warn "kept your existing file as ${LEDS_PATH}.bak-streamdock"
fi
cp "${GEN}/leds.toml" "$LEDS_PATH"

# --- the sync service ---------------------------------------------------------------
if [[ "$CORE_STREAM_DOCK_LED_ENABLED" == "true" ]]; then
  core_log "Installing the ring-colour service"
  mkdir -p "$HOME/.config/stream-dock" "$HOME/.config/systemd/user"
  install -m 600 "${GEN}/led-sync.env" "$HOME/.config/stream-dock/led-sync.env"
  install -m 644 "${GEN}/stream-dock-led-sync.service" \
    "$HOME/.config/systemd/user/stream-dock-led-sync.service"
  # Not fatal if systemd is not answering (a session without a user manager, a
  # container, an ssh login without lingering): the files are installed either way and
  # the unit can be started by hand later. Aborting here would leave the dock set up
  # and the script looking like it failed.
  if ! systemctl --user daemon-reload 2>/dev/null; then
    core_warn "systemctl --user is not available here — the unit is installed but not loaded"
  elif $ENABLE; then
    if systemctl --user enable --now stream-dock-led-sync.service; then
      echo "  started — follow it with: journalctl --user -fu stream-dock-led-sync"
    else
      core_warn "could not start the unit — try: systemctl --user status stream-dock-led-sync"
    fi
  else
    echo "  installed, not started (--no-enable)"
  fi
  # A user unit dies at logout unless lingering is on. Worth saying, not worth doing
  # unasked: enabling lingering is a system-wide change made with sudo, and this is a
  # service for a device on a desk somebody is sitting at.
  if ! loginctl show-user "$USER" --property=Linger 2>/dev/null | grep -q "Linger=yes"; then
    echo "  note: this stops at logout. 'sudo loginctl enable-linger $USER' if you"
    echo "        want it running while logged out."
  fi
else
  core_warn "stream_dock.knob_leds.enabled is false — skipping the ring-colour service"
fi

# --- what a script cannot do for you -------------------------------------------------
core_log "What is left, and only you can do it"

have_opendeck=false
command -v opendeck >/dev/null 2>&1 && have_opendeck=true
flatpak list 2>/dev/null | grep -qi opendeck && have_opendeck=true
$have_opendeck || cat <<'EOF'

  [ ] Install OpenDeck itself:
        flatpak install flathub me.amankhanna.opendeck
EOF

cat <<EOF

  [ ] Install the device plugin, or the dock will not appear in OpenDeck at all —
      an N4 Pro is not an Elgato device and OpenDeck does not speak to it natively:
        https://github.com/aroaxinping/opendeck-akp05   (Ajazz AKP05 / Mirabox N4 family)

  [ ] Install the Home Assistant plugin (a .streamDeckPlugin release, installed
      through OpenDeck's plugin installer):
        https://github.com/cgiesche/streamdeck-homeassistant

  [ ] Put the lighting controls on their own OpenDeck layer, then teach the gate
      how to see it:
        ${DOCK_DIR}/layer-active.sh --discover

  [ ] Find out what makes the knob rings pick up a colour change — two minutes with
      the dock plugged in, and its first test is whether they already do:
        ${DOCK_DIR}/apply-leds.sh --probe

  [ ] Bind the dials and keys — every value to paste is in:
        ${GEN}/bindings.md

  [ ] On the Home Assistant side (from any machine that can ssh to the container host):
        ${DOCK_DIR}/install-ha-package.sh

EOF

if ! lsusb 2>/dev/null | grep -qiE "mirabox|ajazz|stream ?dock"; then
  core_warn "no obviously-Mirabox/Ajazz device in lsusb — if OpenDeck cannot see the dock,"
  core_warn "that is a udev rule question for the device plugin, not for this repo"
fi
