#!/usr/bin/env bash
# Linux laptop simulates Android RSSH device: heartbeat poll + outbound -R + local sshd on 8022.
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
BE_SCRIPTS="$(cd "$(dirname "$0")/../../crash_reporter/backend/scripts" && pwd)"
# shellcheck source=../../crash_reporter/backend/scripts/ra_lib.sh
source "$BE_SCRIPTS/ra_lib.sh"

DEVICE_ID="${RA_DEVICE_ID:-linux-rssh-$(hostname -s)-$$}"
RANDOM_ID="${RA_RANDOM:-rssh-linux-$(date +%s)}"
LOCAL_PORT="${RA_LOCAL_PORT:-8022}"
WORKDIR="${RA_SIM_WORKDIR:-/tmp/rssh-sim-$$}"
SSH_PID=""
DB_PID=""

cleanup() {
  [ -n "$SSH_PID" ] && kill "$SSH_PID" 2>/dev/null || true
  [ -n "$DB_PID" ] && kill "$DB_PID" 2>/dev/null || true
  rm -rf "$WORKDIR"
}
trap cleanup EXIT

mkdir -p "$WORKDIR"
HOST_KEY="$WORKDIR/host_key"

if ! command -v ssh-keygen >/dev/null 2>&1; then
  echo "openssh client required" >&2
  exit 1
fi

echo "== local device SSH on 127.0.0.1:${LOCAL_PORT} =="
ssh-keygen -t ed25519 -f "$HOST_KEY" -N "" -q
/usr/sbin/sshd -D -f /dev/null -h "$HOST_KEY" -p "$LOCAL_PORT" -o AuthorizedKeysFile=/dev/null \
  -o PasswordAuthentication=yes -o PermitRootLogin=no -o UsePAM=no \
  -o AllowUsers="${RA_SSH_USER:-rssh-sim}" 2>/dev/null &
DB_PID=$!
sleep 0.5

echo "== heartbeat enable (tunnel_mode=rssh) =="
export RA_TUNNEL_MODE=rssh
ra_ra_post enable "$DEVICE_ID" "$RANDOM_ID" "linux-sim/1.0" >/tmp/rssh-sim-wait.json
grep -q '"action":"wait"' /tmp/rssh-sim-wait.json && echo OK wait

echo "Operator must whitelist + open session in admin UI, then re-run with RA_SKIP_ADMIN=1"
if [[ "${RA_SKIP_ADMIN:-}" != "1" ]]; then
  echo "Set RA_SKIP_ADMIN=1 after whitelisting device_id=$DEVICE_ID"
  exit 0
fi

echo "== heartbeat connect =="
ra_ra_post enable "$DEVICE_ID" "$RANDOM_ID-b" "linux-sim/1.0" >/tmp/rssh-sim-connect.json
grep -q '"action":"connect"' /tmp/rssh-sim-connect.json || { cat /tmp/rssh-sim-connect.json; exit 1; }
echo OK connect payload

BASTION="$(ra_json -r '.credentials.bastion_host // empty' /tmp/rssh-sim-connect.json)"
BPORT="$(ra_json -r '.credentials.bastion_port // 443' /tmp/rssh-sim-connect.json)"
USER="$(ra_json -r '.credentials.username // empty' /tmp/rssh-sim-connect.json)"
PASS="$(ra_json -r '.credentials.password // empty' /tmp/rssh-sim-connect.json)"
RPORT="$(ra_json -r '.credentials.remote_bind_port // 0' /tmp/rssh-sim-connect.json)"

[ -n "$BASTION" ] && [ -n "$USER" ] && [ "$RPORT" -gt 0 ] || { echo "missing credentials"; exit 1; }

echo "== reverse SSH -R 127.0.0.1:${RPORT}:127.0.0.1:${LOCAL_PORT} =="
sshpass -p "$PASS" ssh -N \
  -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null \
  -p "$BPORT" -R "127.0.0.1:${RPORT}:127.0.0.1:${LOCAL_PORT}" \
  "${USER}@${BASTION}" &
SSH_PID=$!
sleep 2

echo "Tunnel up. Operator on bastion:"
echo "  ssh -p ${RPORT} ${USER}@127.0.0.1"
echo "Press Ctrl+C to stop."
wait "$SSH_PID"
