#!/usr/bin/env bash
# get_gld_slv one-line installer / upgrader from https://gd.g77k.com
# Usage:
#   curl -sSL 'https://gd.g77k.com/api/feeder/install' | sudo bash
#   curl -sSL 'https://gd.g77k.com/api/feeder/install' | sudo GD_API_KEY=gd_xxx bash
set -euo pipefail

BASE="${GD_BASE:-https://gd.g77k.com}"
NAME="${GD_NAME:-get_gld_slv}"
PLATFORM="${GD_PLATFORM:-linux}"
INSTALL_DIR="${GD_INSTALL_DIR:-/usr/local/bin}"
SERVICE="${GD_SERVICE:-$NAME}"
ENV_FILE="${GD_ENV_FILE:-/etc/default/$NAME}"
TMP="${TMPDIR:-/tmp}/.$NAME.install.$$"

die() { echo "ERROR: $*" >&2; exit 1; }
info() { echo "==> $*"; }

if [[ "$(id -u)" -ne 0 ]]; then
  die "run as root (e.g. curl -sSL '...' | sudo bash)"
fi

# --- arch ---
uname_m="$(uname -m)"
case "$uname_m" in
  x86_64|amd64) ARCH="x86_64" ;;
  aarch64|arm64) ARCH="aarch64" ;;
  *) die "unsupported arch: $uname_m (need x86_64 or aarch64)" ;;
esac
[[ "$(uname -s)" == "Linux" ]] || die "this installer supports Linux only"

command -v curl >/dev/null 2>&1 || die "curl is required"
command -v systemctl >/dev/null 2>&1 || die "systemd (systemctl) is required"

AUTH_HDR=()
if [[ -n "${GD_API_KEY:-}" ]]; then
  AUTH_HDR=(-H "X-Api-Key: ${GD_API_KEY}")
fi

DL_URL="${BASE}/api/feeder/download?latest=1&platform=${PLATFORM}&arch=${ARCH}&name=${NAME}"

info "Downloading latest ${NAME} (${PLATFORM}/${ARCH}) from ${BASE}"
mkdir -p "$(dirname "$TMP")"
# Prefer header auth; also pass key= for simple proxies
CURL_OPTS=(-sS -L -o "$TMP" -w "%{http_code}")
if [[ -n "${GD_API_KEY:-}" ]]; then
  CURL_OPTS+=(-H "X-Api-Key: ${GD_API_KEY}" -G --data-urlencode "key=${GD_API_KEY}")
fi
HTTP_CODE=$(curl "${CURL_OPTS[@]}" "$DL_URL" || true)
if [[ "$HTTP_CODE" != "200" ]]; then
  head -c 400 "$TMP" 2>/dev/null || true
  rm -f "$TMP"
  die "download failed (HTTP $HTTP_CODE). Upload a release first (name=${NAME})."
fi
# Reject JSON error bodies masquerading as binary
if head -c 1 "$TMP" | grep -q '{'; then
  head -c 400 "$TMP" || true
  rm -f "$TMP"
  die "download returned JSON error (missing release or bad API key?)"
fi
chmod 0755 "$TMP"

BIN_PATH="${INSTALL_DIR}/${NAME}"
mkdir -p "$INSTALL_DIR"

UPGRADE=0
if [[ -x "$BIN_PATH" ]] || systemctl list-unit-files "${SERVICE}.service" 2>/dev/null | grep -q "${SERVICE}.service"; then
  UPGRADE=1
  info "Existing install detected — upgrading"
  systemctl stop "${SERVICE}.service" 2>/dev/null || true
fi

info "Installing binary → $BIN_PATH"
# atomic replace
mv -f "$TMP" "$BIN_PATH"
chmod 0755 "$BIN_PATH"

# preserve optional env file
if [[ ! -f "$ENV_FILE" ]]; then
  cat > "$ENV_FILE" <<EOF
# Environment for ${NAME} (survives upgrades)
# RUST_LOG=info
# Add app-specific vars below
EOF
  chmod 0644 "$ENV_FILE"
  info "Created $ENV_FILE (edit then: systemctl restart ${SERVICE})"
fi

info "Writing systemd unit ${SERVICE}.service"
cat > "/etc/systemd/system/${SERVICE}.service" <<EOF
[Unit]
Description=${NAME} market data feeder (from ${BASE})
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
EnvironmentFile=-${ENV_FILE}
ExecStart=${BIN_PATH}
Restart=on-failure
RestartSec=5
# Harden lightly; drop privs only if binary does not need root
NoNewPrivileges=true
LimitNOFILE=65535

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable "${SERVICE}.service"
systemctl restart "${SERVICE}.service"
sleep 0.5
if systemctl is-active --quiet "${SERVICE}.service"; then
  VER_HDR=$(curl -sSI "${AUTH_HDR[@]}" "$DL_URL" 2>/dev/null | tr -d '\r' | awk -F': ' 'tolower($1)=="x-feeder-version"{print $2; exit}')
  if [[ "$UPGRADE" -eq 1 ]]; then
    info "Upgrade complete — ${SERVICE} is active (version ${VER_HDR:-unknown})"
  else
    info "Install complete — ${SERVICE} is active (version ${VER_HDR:-unknown})"
  fi
  systemctl --no-pager --full status "${SERVICE}.service" | head -n 12 || true
else
  journalctl -u "${SERVICE}.service" -n 30 --no-pager || true
  die "service failed to start — check: journalctl -u ${SERVICE} -e"
fi

echo
echo "Useful:"
echo "  systemctl status ${SERVICE}"
echo "  journalctl -u ${SERVICE} -f"
echo "  # re-run this installer anytime to upgrade"
echo "  curl -sSL '${BASE}/api/feeder/install' | sudo bash"