#!/data/data/com.termux/files/usr/bin/bash
# Apex Signal — Termux agent setup.
#
# "The daemon is running but there is no agent to connect to" means a Termux
# service started, but the thing the app actually dials — the Apex ADB bridge
# AGENT — was never installed or started. This script installs and starts it.
#
#   curl -fsSL https://tinyradr.lovable.app/agent/termux-setup.sh | bash
#
# Flags:
#   --token <secret>   require this token from the app (recommended)
#   --port <n>         listen port (default 8787)
#   --serial <id>      default adb device when a watch AND a phone are attached
#   --no-boot          skip the Termux:Boot autostart hook
set -euo pipefail

PORT=8787
TOKEN=""
SERIAL=""
BOOT=1
BASE="${APEX_BASE_URL:-https://tinyradr.lovable.app}"
HOME_DIR="${HOME:-/data/data/com.termux/files/home}"
APEX_DIR="$HOME_DIR/apex-agent"

while [ $# -gt 0 ]; do
  case "$1" in
    --token) TOKEN="$2"; shift 2 ;;
    --port) PORT="$2"; shift 2 ;;
    --serial) SERIAL="$2"; shift 2 ;;
    --no-boot) BOOT=0; shift ;;
    -h|--help) sed -n '2,14p' "$0"; exit 0 ;;
    *) echo "unknown option: $1"; exit 1 ;;
  esac
done

say() { printf '\n[apex] %s\n' "$*"; }

say "installing node, adb and curl"
pkg update -y >/dev/null 2>&1 || true
pkg install -y nodejs-lts android-tools curl termux-api >/dev/null

mkdir -p "$APEX_DIR"
cd "$APEX_DIR"

say "installing the websocket library"
[ -f package.json ] || echo '{"name":"apex-agent","private":true,"type":"module"}' > package.json
npm install ws --no-audit --no-fund >/dev/null

say "downloading the bridge agent"
curl -fsSL "$BASE/agent/adb-bridge-agent.mjs" -o adb-bridge-agent.mjs

# Stop an older copy so the port is free.
pkill -f adb-bridge-agent.mjs >/dev/null 2>&1 || true

ARGS=(--port "$PORT")
[ -n "$TOKEN" ] && ARGS+=(--token "$TOKEN")
[ -n "$SERIAL" ] && ARGS+=(--serial "$SERIAL")

cat > start-agent.sh <<EOF
#!/data/data/com.termux/files/usr/bin/bash
cd "$APEX_DIR"
exec node adb-bridge-agent.mjs ${ARGS[*]}
EOF
chmod +x start-agent.sh

if [ "$BOOT" = "1" ]; then
  mkdir -p "$HOME_DIR/.termux/boot"
  cat > "$HOME_DIR/.termux/boot/apex-agent" <<EOF
#!/data/data/com.termux/files/usr/bin/sh
termux-wake-lock
"$APEX_DIR/start-agent.sh"
EOF
  chmod +x "$HOME_DIR/.termux/boot/apex-agent"
  say "autostart installed (needs the Termux:Boot app installed once)"
fi

say "starting the agent"
nohup ./start-agent.sh > "$APEX_DIR/agent.log" 2>&1 &
sleep 3

if ! curl -fsS "http://127.0.0.1:$PORT/health" >/dev/null 2>&1; then
  say "agent did NOT come up — last lines of the log:"
  tail -n 20 "$APEX_DIR/agent.log" || true
  exit 1
fi

IP=$(ip route get 1.1.1.1 2>/dev/null | grep -oE 'src [0-9.]+' | awk '{print $2}' | head -1)
[ -z "${IP:-}" ] && IP="<phone-lan-ip>"

say "AGENT IS UP"
curl -fsS "http://127.0.0.1:$PORT/health" || true
cat <<EOF

  Put this in the app's bridge settings:

      ws://$IP:$PORT/adb
EOF
[ -n "$TOKEN" ] && echo "      token: $TOKEN"
cat <<'EOF'

  IMPORTANT — the published app is served over HTTPS, and a browser will not
  let an HTTPS page open a plain ws:// socket. To reach this agent either:

    * open the app over http on the same phone/LAN, or
    * run the agent with a real certificate:
        node adb-bridge-agent.mjs --cert fullchain.pem --key privkey.pem
      and use wss:// in the settings.

  The ambient sensing panel needs none of this and works on its own.

  Restart later:  ~/apex-agent/start-agent.sh
  Log:            ~/apex-agent/agent.log
  Health:         curl http://127.0.0.1:8787/health
EOF
