#!/usr/bin/env bash
set -euo pipefail

BASE="https://yuranetwork.com"
TMP="${TMPDIR:-/tmp}/yura-connect"
mkdir -p "$TMP"

info(){ printf "[Yura] %s\n" "$*"; }
warn(){ printf "[Yura] %s\n" "$*" >&2; }

need_cmd(){ command -v "$1" >/dev/null 2>&1; }

if ! need_cmd curl; then
  echo "curl is required"; exit 1
fi

if ! need_cmd jq; then
  warn "jq not found. Installing..."
  if need_cmd apt-get; then sudo apt-get update -y >/dev/null && sudo apt-get install -y jq >/dev/null
  elif need_cmd brew; then brew install jq >/dev/null
  else echo "Please install jq and re-run."; exit 1; fi
fi

if ! need_cmd wg; then
  warn "WireGuard tools not found. Installing..."
  if need_cmd apt-get; then sudo apt-get update -y >/dev/null && sudo apt-get install -y wireguard wireguard-tools >/dev/null
  elif need_cmd brew; then brew install wireguard-tools >/dev/null
  else echo "Please install wireguard-tools and re-run."; exit 1; fi
fi

info "Requesting one-time login token..."
GEN=$(curl -fsS -X POST "$BASE/api/token/generate")
TOKEN_ID=$(echo "$GEN" | jq -r .tokenId)
TOKEN_SECRET=$(echo "$GEN" | jq -r .tokenSecret)

[ -n "$TOKEN_ID" ] && [ "$TOKEN_ID" != "null" ] || { echo "Failed to get token"; exit 1; }

info "Token generated: $TOKEN_ID"
BODY=$(jq -cn --arg id "$TOKEN_ID" --arg sec "$TOKEN_SECRET" '{tokenId:$id, tokenSecret:$sec}')

CONF="$TMP/yura-client.conf"
info "Downloading WireGuard config..."
curl -fsS -X POST "$BASE/api/token/wg-config" -H 'Content-Type: application/json' -d "$BODY" -o "$CONF"

info "Authorizing connection..."
CONNECT=$(curl -fsS -X POST "$BASE/api/token/connect" -H 'Content-Type: application/json' -d "$BODY")

sudo mkdir -p /etc/wireguard
sudo cp "$CONF" /etc/wireguard/yura-client.conf

info "Starting tunnel..."
if command -v systemctl >/dev/null 2>&1; then
  sudo systemctl enable wg-quick@yura-client >/dev/null 2>&1 || true
  sudo systemctl restart wg-quick@yura-client
else
  sudo wg-quick down /etc/wireguard/yura-client.conf >/dev/null 2>&1 || true
  sudo wg-quick up /etc/wireguard/yura-client.conf
fi

info "Installing Yura Root CA trust..."
curl -fsS "$BASE/api/ca/root.crt" -o "$TMP/yura-root-ca.crt"
if need_cmd update-ca-certificates; then
  sudo cp "$TMP/yura-root-ca.crt" /usr/local/share/ca-certificates/yura-root-ca.crt
  sudo update-ca-certificates >/dev/null
elif need_cmd security; then
  sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain "$TMP/yura-root-ca.crt" || true
else
  warn "Could not auto-install CA. Install $TMP/yura-root-ca.crt manually."
fi

PUB_ID=$(echo "$CONNECT" | jq -r '.permanentPublisher.publisherId // empty')
PUB_KEY=$(echo "$CONNECT" | jq -r '.permanentPublisher.publisherKey // empty')
if [ -n "$PUB_ID" ]; then
  cat > "$TMP/yura-publisher.json" <<EOF
{"publisherId":"$PUB_ID","publisherKey":"$PUB_KEY"}
EOF
  info "Permanent Publisher Key saved: $TMP/yura-publisher.json"
  echo "Publisher ID: $PUB_ID"
  echo "Publisher Key: $PUB_KEY"
fi

info "Connected to Yura Network."
echo "Open: https://yuranetwork.yura"
