#!/bin/bash
# Remote Desktop Agent Launcher
CONFIG_FILE="/etc/remotedesktop/config.json"
HUB_URL="https://pdfvier.online"
TOKEN=""
PORT="8080"

if [ -f "$CONFIG_FILE" ]; then
  CONF_HUB=$(grep -o '"hub_url"[^,]*' "$CONFIG_FILE" 2>/dev/null | cut -d'"' -f4)
  if [ -n "$CONF_HUB" ]; then HUB_URL="$CONF_HUB"; fi
  CONF_TOKEN=$(grep -o '"token"[^,]*' "$CONFIG_FILE" 2>/dev/null | cut -d'"' -f4)
  if [ -n "$CONF_TOKEN" ]; then TOKEN="$CONF_TOKEN"; fi
  CONF_PORT=$(grep -o '"port"[^,}]*' "$CONFIG_FILE" 2>/dev/null | grep -o '[0-9]*')
  if [ -n "$CONF_PORT" ]; then PORT="$CONF_PORT"; fi
fi

TOKEN_ARG=""
if [ -n "$TOKEN" ]; then
  TOKEN_ARG="--token $TOKEN"
fi

DAEMON_MODE=0
PID_FILE="/tmp/remotedesktop-agent.pid"

while [[ $# -gt 0 ]]; do
  case "$1" in
    --hub-url) HUB_URL="$2"; shift 2 ;;
    --token) TOKEN_ARG="--token $2"; shift 2 ;;
    --port) PORT="$2"; shift 2 ;;
    --daemon|-d|start) DAEMON_MODE=1; shift ;;
    stop)
      if [ -f "$PID_FILE" ]; then
        PID=$(cat "$PID_FILE")
        kill "$PID" 2>/dev/null && rm -f "$PID_FILE"
        echo "[RemoteDesktopAgent] Stopped background process (PID: $PID)."
      fi
      exit 0
      ;;
    status)
      if [ -f "$PID_FILE" ] && kill -0 "$(cat "$PID_FILE")" 2>/dev/null; then
        echo "[RemoteDesktopAgent] Running in background (PID: $(cat "$PID_FILE"))."
      else
        echo "[RemoteDesktopAgent] Not running."
      fi
      exit 0
      ;;
    *) break ;;
  esac
done

# Wait up to 25 seconds on boot for graphical display server socket to become available
for i in $(seq 1 25); do
  if ls /tmp/.X11-unix/X* >/dev/null 2>&1 || [ -n "$DISPLAY" ]; then
    break
  fi
  sleep 1
done

# Dynamic X11 Display & Authority auto-detection for systemd daemon
CURR_UID=$(id -u)
if [ "$CURR_UID" -eq 0 ]; then
  if command -v loginctl >/dev/null 2>&1; then
    DESK_USER=$(loginctl list-sessions --no-legend 2>/dev/null | awk '{print $3}' | grep -v 'root\|gdm\|lightdm' | head -n1)
    if [ -n "$DESK_USER" ]; then CURR_UID=$(id -u "$DESK_USER" 2>/dev/null || echo 0); fi
  fi
  if [ "$CURR_UID" -eq 0 ]; then
    CURR_UID=$(awk -F: '$3 >= 1000 && $3 < 60000 {print $3}' /etc/passwd | head -n1)
  fi
fi

DETECTED_DISP=""
if command -v loginctl >/dev/null 2>&1; then
  for s in $(loginctl list-sessions --no-legend 2>/dev/null | awk '{print $1}'); do
    if [ "$(loginctl show-session "$s" -p User --value 2>/dev/null)" = "$CURR_UID" ]; then
      D_VAL=$(loginctl show-session "$s" -p Display --value 2>/dev/null)
      if [ -n "$D_VAL" ]; then DETECTED_DISP="$D_VAL"; break; fi
    fi
  done
fi

if [ -z "$DETECTED_DISP" ]; then
  # Sort reverse version so user desktop :1 is chosen before login greeter :0
  DETECTED_DISP=$(ls /tmp/.X11-unix/X* 2>/dev/null | sort -V -r | head -n1 | sed 's|/tmp/.X11-unix/X|:|')
fi

export DISPLAY="${DETECTED_DISP:-:1}"

if [ -z "$XAUTHORITY" ] || [ ! -f "$XAUTHORITY" ]; then
  for auth in "/run/user/$CURR_UID/gdm/Xauthority"               "/run/user/$CURR_UID/.mutter-Xwaylandauth"*               "/run/user/$CURR_UID/xauth"*               "$HOME/.Xauthority"               /home/*/.Xauthority; do
    if [ -f "$auth" ] && [ -r "$auth" ]; then
      export XAUTHORITY="$auth"
      break
    fi
  done
  if [ -z "$XAUTHORITY" ] || [ ! -f "$XAUTHORITY" ]; then
    RUN_AUTH=$(find "/run/user/$CURR_UID" -type f -name "*Xauthority*" -readable 2>/dev/null | head -n1)
    if [ -n "$RUN_AUTH" ]; then
      export XAUTHORITY="$RUN_AUTH"
    fi
  fi
fi

export PYTHONUNBUFFERED=1

PYTHON="python3"
if [ -x "/opt/remotedesktop/venv/bin/python3" ]; then
  PYTHON="/opt/remotedesktop/venv/bin/python3"
elif [ -x "$HOME/.remote-desktop/venv/bin/python3" ]; then
  PYTHON="$HOME/.remote-desktop/venv/bin/python3"
fi

echo "[RemoteDesktopAgent] Connecting to $HUB_URL on port $PORT (Display: $DISPLAY)..."

if [ "$DAEMON_MODE" -eq 1 ]; then
  LOG_FILE="/tmp/remotedesktop-agent.log"
  nohup "$PYTHON" /opt/remotedesktop/phase1/web_gateway.py --port "$PORT" --hub-url "$HUB_URL" $TOKEN_ARG "$@" > "$LOG_FILE" 2>&1 &
  AGENT_PID=$!
  echo "$AGENT_PID" > "$PID_FILE"
  echo "[RemoteDesktopAgent] ✅ Started in background (PID: $AGENT_PID) — Independent of terminal."
  echo "[RemoteDesktopAgent] Logs: $LOG_FILE | Stop with: remotedesktop-agent stop"
  exit 0
fi

exec "$PYTHON" /opt/remotedesktop/phase1/web_gateway.py --port "$PORT" --hub-url "$HUB_URL" $TOKEN_ARG "$@"
