#!/usr/bin/env bash
# aRDee Linux command-line entry point.  The desktop app is the product; this
# helper remains for administrators who want status/stop commands in a terminal.
set -euo pipefail

ROOT="${ARDEE_ROOT:-/opt/aRDee}"
AGENT="$ROOT/rd-agent"
USER_ROOT="$HOME/.local/share/aRDee"
USER_AGENT="$USER_ROOT/rd-agent"
SERVICE_DIR="$HOME/.config/systemd/user"
SERVICE="$SERVICE_DIR/ardee-agent.service"
host_backend=''
host_desktop=''

# Both desktop launches and generated host services use the same selection.
# Read real binary metadata, never caller-supplied RD_APP_* overrides. A broken
# probe cannot hang startup or fill memory, and a partial pair cannot win.
runtime_version() {
  local candidate="$1" output
  [ -x "$candidate/aRDee" ] && [ -x "$candidate/rd-agent" ] || return 1
  output="$(timeout 3 env -u RD_APP_VERSION -u RD_APP_BUILD "$candidate/rd-agent" --version 2>/dev/null | head -c 513)" || return 1
  [ "${#output}" -le 512 ] || return 1
  # The bounded git-describe label is display metadata, not an ordering or trust
  # input. Do not reject an official build merely because its tag has a new shape.
  local pattern='^rd-agent ([0-9]{1,9})\.([0-9]{1,9})\.([0-9]{1,9}) \(build ([0-9]{1,15}), commit [A-Za-z0-9._/+:-]{1,128}\)$'
  [[ "$output" =~ $pattern ]] || return 1
  [ "$((10#${BASH_REMATCH[4]}))" -gt 0 ] || return 1
  printf '%s %s %s %s\n' "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}" "${BASH_REMATCH[3]}" "${BASH_REMATCH[4]}"
}

select_runtime() {
  # An AppImage/extracted bundle explicitly owns its runtime and must never
  # borrow a Debian/user pair or probe it during portable startup.
  if [ -n "${ARDEE_ROOT:-}" ]; then
    [ -x "$ROOT/aRDee" ] && [ -x "$ROOT/rd-agent" ] || {
      echo 'aRDee portable app or host files are missing. Download the complete bundle again.' >&2
      return 1
    }
    printf '%s\n' "$ROOT"
    return
  fi
  local system_version user_version
  system_version="$(runtime_version "$ROOT")" || system_version=''
  user_version="$(runtime_version "$USER_ROOT")" || user_version=''
  if [ -z "$system_version" ] && [ -z "$user_version" ]; then
    echo 'No complete aRDee runtime with a valid version was found. Reinstall the current package.' >&2
    return 1
  fi
  if [ -z "$system_version" ]; then printf '%s\n' "$USER_ROOT"; return; fi
  if [ -z "$user_version" ]; then printf '%s\n' "$ROOT"; return; fi
  local sm sn sp sb um un up ub
  read -r sm sn sp sb <<< "$system_version"
  read -r um un up ub <<< "$user_version"
  # Releases advance version AND build. Reject a conflicting pair instead of
  # silently downgrading one dimension. Equal pairs prefer the package copy.
  local version_order=0 left right pair
  for pair in "$um:$sm" "$un:$sn" "$up:$sp"; do
    left="${pair%%:*}"; right="${pair#*:}"
    if (( 10#$left > 10#$right )); then version_order=1; break; fi
    if (( 10#$left < 10#$right )); then version_order=-1; break; fi
  done
  if (( (version_order > 0 && 10#$ub < 10#$sb) || (version_order < 0 && 10#$ub > 10#$sb) )); then
    echo 'aRDee runtime version/build metadata conflicts. Reinstall the current package before starting.' >&2
    return 1
  fi
  if (( version_order > 0 || (version_order == 0 && 10#$ub > 10#$sb) )); then
    printf '%s\n' "$USER_ROOT"
  else
    printf '%s\n' "$ROOT"
  fi
}

usage() {
  cat <<'EOF'
Usage: ardee-linux [open|enroll|remote-claim-request|remote-claim-complete|status|stop]
  open    Open the native aRDee desktop app (default).
  enroll  Sign this Linux computer in. X11 starts hosting; Omarchy waits for local setup.
  remote-claim-request   Prepare passwordless enrollment from another signed-in aRDee device.
  remote-claim-complete  Finish a remote enrollment after its owner approves it.
  status  Show whether this computer is connected.
  stop    Stop its aRDee host service.
EOF
}

install_agent() {
  if [[ "$(printf '%s' "$host_desktop" | tr '[:upper:]' '[:lower:]')" == *gnome* ]] \
      && [ ! -x /usr/bin/gnome-screenshot ]; then
    echo "aRDee needs GNOME Screenshot to show this computer's lock screen safely. Install the .deb package from Get the App, which includes that requirement, then try again." >&2
    exit 1
  fi
  local service_state selected_runtime dispatcher existing expected candidate legacy_expected
  service_state="$(systemctl --user is-active ardee-agent.service 2>/dev/null)" || true
  case "$service_state" in
    inactive|failed|unknown) ;;
    *) echo 'End remote sessions and stop the existing aRDee host before enrolling again; its inactive state could not be verified.' >&2; return 1 ;;
  esac
  selected_runtime="$(select_runtime)"
  dispatcher="$USER_ROOT/ardee-linux"
  mkdir -p "$USER_ROOT" "$SERVICE_DIR"
  if [ -e "$SERVICE" ] || [ -L "$SERVICE" ]; then
    [ -f "$SERVICE" ] && [ ! -L "$SERVICE" ] || { echo 'A linked or non-regular aRDee host service was preserved.' >&2; return 1; }
    existing="$(cat "$SERVICE")"
    local generated=0
    for candidate in "$USER_AGENT" '/opt/aRDee/rd-agent' "\"$dispatcher\""; do
      expected="$(printf '[Unit]\nDescription=aRDee remote desktop host\nAfter=graphical-session.target\n\n[Service]\nExecStart=%s run\nRestart=on-failure\nRestartSec=5\n\n[Install]\nWantedBy=default.target\n' "$candidate")"
      legacy_expected="${expected/Restart=on-failure/# A Wayland session exits cleanly because it is not a safe host.  Do not spin$'\n'# forever and consume the desktop just to retry an unsupported capability.$'\n'Restart=on-failure}"
      if [ "$existing" = "$expected" ] || [ "$existing" = "$legacy_expected" ]; then generated=1; break; fi
    done
    if [ "$generated" != 1 ]; then
      echo 'An existing custom aRDee host service was preserved. Review it before enrolling again.' >&2
      return 1
    fi
  fi
  if [ "$selected_runtime" != "$USER_ROOT" ]; then
    install -m 0755 "$selected_runtime/rd-agent" "$USER_AGENT"
    install -m 0755 "$selected_runtime/aRDee" "$USER_ROOT/aRDee"
  fi
  if [ "${BASH_SOURCE[0]}" != "$dispatcher" ]; then
    install -m 0755 "${BASH_SOURCE[0]}" "$dispatcher"
  fi
  # A systemd *user* service is crucial: the screen and keyboard belong to the
  # signed-in desktop user, never to root. Import the live GUI variables before
  # starting it so X11 access survives terminal-to-service handoff.
  cat > "$SERVICE" <<EOF
[Unit]
Description=aRDee remote desktop host
After=graphical-session.target

[Service]
ExecStart="$dispatcher" run
Restart=on-failure
RestartSec=5

[Install]
WantedBy=default.target
EOF
  # Preserve the complete GUI-session identity. `detect_host_backend` already
  # proved this is an X11 session from logind; these inherited variables are
  # connection details only, never a way to choose a host backend.
  systemctl --user import-environment DISPLAY XAUTHORITY XDG_SESSION_TYPE XDG_CURRENT_DESKTOP XDG_SESSION_DESKTOP WAYLAND_DISPLAY XDG_RUNTIME_DIR HYPRLAND_INSTANCE_SIGNATURE DBUS_SESSION_BUS_ADDRESS 2>/dev/null || true
}

active_graphical_session() {
  local session_id=''
  if command -v loginctl >/dev/null 2>&1 && [[ -n "${USER:-}" ]]; then
    session_id="$(loginctl show-user "$USER" -p Display --value 2>/dev/null || true)"
  fi
  printf '%s' "$session_id"
}

# A remote shell can inherit arbitrary GUI variables, so only the logged-in
# graphical session named by logind selects the desktop/backend. This keeps an
# SSH request from turning another Wayland compositor into an Omarchy host.
detect_host_backend() {
  local session_id session_type session_type_normalized desktop_normalized
  session_id="$(active_graphical_session)"
  host_backend=''
  host_desktop=''
  if [[ -z "$session_id" ]]; then
    echo "NO GO: no active graphical desktop session was found for this account. Sign in locally first, then try again." >&2
    return 2
  fi
  session_type="$(loginctl show-session "$session_id" -p Type --value 2>/dev/null || true)"
  host_desktop="$(loginctl show-session "$session_id" -p Desktop --value 2>/dev/null || true)"
  session_type_normalized="$(printf '%s' "$session_type" | tr '[:upper:]' '[:lower:]')"
  desktop_normalized="$(printf '%s' "$host_desktop" | tr '[:upper:]' '[:lower:]')"
  case "$session_type_normalized" in
    x11)
      host_backend='x11'
      ;;
    wayland)
      if [[ "$desktop_normalized" == *hyprland* || "$desktop_normalized" == *omarchy* ]]; then
        host_backend='hyprland'
      else
        echo "NO GO: this Wayland desktop cannot host unattended aRDee control. It can still use aRDee to control another supported computer." >&2
        return 2
      fi
      ;;
    *)
      echo "NO GO: the active desktop session is not an X11/Xorg or supported Omarchy session." >&2
      return 2
      ;;
  esac
}

prepare_x11_host_environment() {
  detect_host_backend
  if [[ "$host_backend" != 'x11' ]]; then
    echo "NO GO: this command cannot start unattended hosting from the active desktop session." >&2
    return 2
  fi
  local session_id display
  session_id="$(active_graphical_session)"
  display="$(loginctl show-session "$session_id" -p Display --value 2>/dev/null || true)"
  # GDM's Xorg autologin session can omit logind's Display property.
  # Backend eligibility was established above from logind, never shell input.
  # Read connection details from this user's desktop service manager, without
  # evaluating its output as shell code.
  local gui_env line authority=''
  gui_env="$(systemctl --user show-environment 2>/dev/null || true)"
  while IFS= read -r line; do
    case "$line" in
      DISPLAY=*) [[ -n "$display" ]] || display="${line#DISPLAY=}" ;;
      XAUTHORITY=*) authority="${line#XAUTHORITY=}" ;;
    esac
  done <<< "$gui_env"
  if [[ "$authority" == /* && -f "$authority" && -O "$authority" ]]; then
    export XAUTHORITY="$authority"
  fi
  if [[ ! "$display" =~ ^:[0-9]+(\.[0-9]+)?$ ]]; then
    echo "NO GO: the active X11 display could not be identified. Open a local X11 desktop session, then try again." >&2
    return 2
  fi
  export DISPLAY="$display"
  if [[ -z "${XAUTHORITY:-}" && -f "$HOME/.Xauthority" ]]; then
    export XAUTHORITY="$HOME/.Xauthority"
  fi
}

prepare_identity_enrollment() {
  detect_host_backend
  if [[ "$host_backend" == 'x11' ]]; then
    prepare_x11_host_environment
  fi
}

finish_identity_enrollment() {
  case "$host_backend" in
    x11)
      systemctl --user daemon-reload
      systemctl --user enable --now ardee-agent.service
      echo "This computer is now available in aRDee. Open https://ardee.help/portal.html to connect."
      ;;
    hyprland)
      echo "This computer is linked to aRDee, but hosting is off."
      echo "Open the native aRDee app on this computer and choose Set up & Start to approve screen sharing locally."
      echo "This command cannot approve screen sharing or start hosting remotely."
      ;;
  esac
}

case "${1:-open}" in
  open|run)
    selected_runtime="$(select_runtime)"
    if [ "${1:-open}" = run ]; then
      # Strip stale GUI version overrides from inherited systemd environments.
      # Eligibility/consent checks remain inside the selected agent's run path.
      exec env -u RD_APP_VERSION -u RD_APP_BUILD "$selected_runtime/rd-agent" run
    fi
    exec "$selected_runtime/aRDee"
    ;;
  enroll)
    [ -x "$AGENT" ] || { echo "aRDee host files are missing. Reinstall the package." >&2; exit 1; }
    prepare_identity_enrollment
    if [[ "$host_backend" == 'x11' ]]; then
      command -v xdotool >/dev/null || { echo "xdotool is required for Linux mouse and keyboard control. Reinstall the aRDee package." >&2; exit 1; }
      install_agent
    fi
    read -r -p "aRDee email: " EMAIL
    read -r -s -p "Password: " PASSWORD; echo
    read -r -p "Computer name [$(hostname)]: " NAME
    NAME="${NAME:-$(hostname)}"
    if [[ "$host_backend" == 'x11' ]]; then
      printf '%s\n' "$PASSWORD" | "$USER_AGENT" enroll --server https://ardee.help --email "$EMAIL" --name "$NAME" --password-stdin
    else
      printf '%s\n' "$PASSWORD" | "$AGENT" enroll --server https://ardee.help --email "$EMAIL" --name "$NAME" --password-stdin
    fi
    unset PASSWORD
    finish_identity_enrollment
    ;;
  remote-claim-request)
    [ -x "$AGENT" ] || { echo "aRDee host files are missing. Reinstall the package." >&2; exit 1; }
    prepare_identity_enrollment
    "$AGENT" remote-claim-request --server https://ardee.help --name "$(hostname)"
    if [[ "$host_backend" == 'hyprland' ]]; then
      echo "This Omarchy computer can be linked after approval, but hosting stays off until someone opens the native app locally and chooses Set up & Start."
    fi
    ;;
  remote-claim-complete)
    [ -x "$AGENT" ] || { echo "aRDee host files are missing. Reinstall the package." >&2; exit 1; }
    prepare_identity_enrollment
    if [[ "$host_backend" == 'x11' ]]; then
      install_agent
      "$USER_AGENT" remote-claim-complete --server https://ardee.help
    else
      "$AGENT" remote-claim-complete --server https://ardee.help
    fi
    finish_identity_enrollment
    ;;
  status)
    systemctl --user status ardee-agent.service --no-pager
    ;;
  stop)
    systemctl --user disable --now ardee-agent.service
    ;;
  -h|--help|help) usage ;;
  *) usage >&2; exit 2 ;;
esac
