#!/usr/bin/env bash
# Shared helpers for remote-access CLI validation (device + operator).
# Mirrors Android RemoteAccessService heartbeat payloads.
set -euo pipefail

RA_LIB_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

ra_json() {
  if command -v jq >/dev/null 2>&1; then
    jq -r "$@"
  else
    echo "jq required for: $*" >&2
    return 1
  fi
}

ra_base() {
  echo "${CRASHES_BASE:-http://127.0.0.1:8080/app/androidcast_project/crashes}"
}

ra_heartbeat_url() {
  echo "$(ra_base)/api/heartbeat.php"
}

ra_admin_url() {
  local action="${1:-}"
  echo "$(ra_base)/api/remote_access.php?action=${action}"
}

# POST heartbeat type:ra — prints full JSON response to stdout.
# Usage: ra_ra_post enable|disable DEVICE_ID RANDOM [app_version]
ra_ra_post() {
  local status="$1"
  local device_id="$2"
  local random="${3:-}"
  local app_version="${4:-cli-sim}"
  local mode="${RA_TUNNEL_MODE:-wireguard}"
  local caps
  if [[ "$mode" == "rssh" ]]; then
    caps='["rssh","shell"]'
  else
    caps='["wireguard","files_app_home"]'
  fi
  local body
  body=$(printf '{"heartbeat":{"type":"ra","status":"%s","device_id":"%s","random":"%s","app_version":"%s","tunnel_mode":"%s","capabilities":%s}}' \
    "$status" "$device_id" "$random" "$app_version" "$mode" "$caps")
  local url body_tmp code
  url="$(ra_heartbeat_url)"
  body_tmp="$(mktemp)"
  code=$(curl -sS -o "$body_tmp" -w '%{http_code}' -X POST -H 'Content-Type: application/json' -d "$body" "$url")
  if [[ "$code" != "200" ]]; then
    echo "heartbeat HTTP $code from $url" >&2
    cat "$body_tmp" >&2
    rm -f "$body_tmp"
    return 1
  fi
  cat "$body_tmp"
  rm -f "$body_tmp"
}

ra_ra_action() {
  ra_ra_post "$@" | ra_json -r '.heartbeat.action // empty'
}

ra_admin_login() {
  local jar="${1:?cookie jar}"
  local user="${ADMIN_USER:-admin}"
  local pass="${ADMIN_PASS:-admin}"
  curl -sf -c "$jar" -b "$jar" -X POST \
    -d "username=${user}&password=${pass}" \
    "$(ra_base)/login" >/dev/null
}

ra_admin_post() {
  local jar="$1"
  local action="$2"
  local json_body="$3"
  curl -sf -b "$jar" -c "$jar" -X POST -H 'Content-Type: application/json' \
    -d "$json_body" "$(ra_admin_url "$action")"
}

# Build wireguard-quick config from connect JSON (same fields as WireGuardConfigBuilder.java).
ra_wg_quick_from_connect() {
  local connect_json="$1"
  if ! command -v jq >/dev/null 2>&1; then
    return 1
  fi
  local priv addr peer_pub endpoint allowed
  priv=$(echo "$connect_json" | jq -r '.heartbeat.credentials.interface_private_key // empty')
  addr=$(echo "$connect_json" | jq -r '.heartbeat.credentials.interface_address // "172.200.2.10/32"')
  peer_pub=$(echo "$connect_json" | jq -r '.heartbeat.credentials.peer_public_key // empty')
  endpoint=$(echo "$connect_json" | jq -r '.heartbeat.endpoint // .heartbeat.credentials.peer_endpoint // empty')
  allowed=$(echo "$connect_json" | jq -r '.heartbeat.credentials.peer_allowed_ips // "0.0.0.0/0"')
  if [[ -z "$priv" || -z "$peer_pub" ]]; then
    return 1
  fi
  cat <<EOF
[Interface]
PrivateKey = ${priv}
Address = ${addr}

[Peer]
PublicKey = ${peer_pub}
EOF
  if [[ -n "$endpoint" ]]; then
    echo "Endpoint = ${endpoint}"
  fi
  echo "AllowedIPs = ${allowed}"
  echo "PersistentKeepalive = 25"
}
