#!/usr/bin/env bash
# DVeVPN — always installs the latest Stable release.
#   curl -fsSL https://dveproto.serversys.ru/install.sh | sudo bash
#
# This file is a bootstrap only. It must NEVER fetch itself.
set -euo pipefail

API="${DVE_VERSION_API:-https://dveproto.serversys.ru/api/version}"
CHANNEL="${DVE_CHANNEL:-2.0}"
INSTALLER="https://dveproto.serversys.ru/dvevpn/${CHANNEL}/install.sh"

echo "==> DVeVPN Stable installer"

BODY="$(mktemp)"
trap 'rm -f "$BODY"' EXIT

STABLE=""
if curl -fsSL "$API" -o "$BODY" 2>/dev/null; then
  if command -v python3 >/dev/null 2>&1; then
    STABLE="$(python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(d.get("stable") or "")' "$BODY" 2>/dev/null || true)"
    CH="$(python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(d.get("channel") or "")' "$BODY" 2>/dev/null || true)"
    if [[ -n "$CH" ]]; then
      CHANNEL="$CH"
      INSTALLER="https://dveproto.serversys.ru/dvevpn/${CHANNEL}/install.sh"
    fi
  fi
fi

if [[ -n "$STABLE" ]]; then
  echo "    stable ${STABLE}"
fi

echo "==> Fetching ${INSTALLER}"
curl -fsSL "$INSTALLER" -o "$BODY"
if head -c 15 "$BODY" | grep -qi '<!DOCTYPE\|<html'; then
  echo "error: ${INSTALLER} returned HTML" >&2
  exit 1
fi
if head -n 5 "$BODY" | grep -q 'This file is a bootstrap only'; then
  echo "error: refused to re-exec bootstrap installer (loop)" >&2
  exit 1
fi
exec bash "$BODY" "$@"
