#!/usr/bin/env sh
# pgdiscover installer — the 2-minute path.
#
#   curl -fsSL https://get.bareket.ai/pgdiscover | sh
#
# Detects OS/arch, downloads the matching static binary from get.bareket.ai,
# verifies its SHA-256, and installs to ~/.local/bin (or $PGDISCOVER_BIN_DIR).
# No root, no dependencies. The source repo is private; distribution is the site.
# For air-gapped hosts, copy the binary by hand instead.
set -eu

BASE="${PGDISCOVER_BASE:-https://get.bareket.ai}"
VERSION="${PGDISCOVER_VERSION:-latest}"
BIN_DIR="${PGDISCOVER_BIN_DIR:-$HOME/.local/bin}"

say() { printf '%s\n' "pgdiscover-install: $*" >&2; }
die() { say "$*"; exit 1; }

os="$(uname -s | tr '[:upper:]' '[:lower:]')"
case "$os" in
  linux) os=linux ;;
  darwin) os=darwin ;;
  *) die "unsupported OS: $os (copy the binary manually)" ;;
esac

arch="$(uname -m)"
case "$arch" in
  x86_64|amd64) arch=amd64 ;;
  arm64|aarch64) arch=arm64 ;;
  *) die "unsupported arch: $arch" ;;
esac

# Resolve version. get.bareket.ai/dl/latest is a one-line text file with the
# current version (e.g. "0.1.0").
if [ "$VERSION" = "latest" ]; then
  ver="$(curl -fsSL "${BASE}/dl/latest" 2>/dev/null | tr -d ' \t\r\n')"
  [ -n "${ver:-}" ] || die "could not resolve latest version from ${BASE}/dl/latest (set PGDISCOVER_VERSION)"
else
  ver="${VERSION#v}"
fi

asset="pgdiscover_${ver}_${os}_${arch}"
url="${BASE}/dl/${asset}"
sums="${BASE}/dl/SHA256SUMS_${ver}.txt"

tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT
say "downloading $asset ($ver)"
curl -fsSL "$url" -o "$tmp/pgdiscover" || die "download failed: $url"

# verify checksum when the sums file is available
if curl -fsSL "$sums" -o "$tmp/sums.txt" 2>/dev/null; then
  want="$(grep " ${asset}\$" "$tmp/sums.txt" | awk '{print $1}')"
  if [ -n "${want:-}" ]; then
    if command -v sha256sum >/dev/null 2>&1; then got="$(sha256sum "$tmp/pgdiscover" | awk '{print $1}')"; else got="$(shasum -a 256 "$tmp/pgdiscover" | awk '{print $1}')"; fi
    [ "$want" = "$got" ] || die "checksum mismatch (want $want, got $got)"
    say "checksum ok"
  fi
else
  say "warning: checksum file unavailable, skipping verification"
fi

mkdir -p "$BIN_DIR"
chmod +x "$tmp/pgdiscover"
mv "$tmp/pgdiscover" "$BIN_DIR/pgdiscover"
say "installed → $BIN_DIR/pgdiscover ($ver)"

case ":$PATH:" in
  *":$BIN_DIR:"*) ;;
  *) say "add to PATH:  export PATH=\"$BIN_DIR:\$PATH\"" ;;
esac

say "next:  pgdiscover up --cidr <your-bmc-subnet> --insecure"
