#!/usr/bin/env bash
# TWCP installer — curl | bash
# Usage:
#   curl -fsSL https://www.tamfitronics.com/release/twcp/assets/install-curl-v4.sh | bash
#   curl -fsSL ... | bash -s v0.3.1        # pin a version
#   TARGET_DIR=/opt/twcp curl ... | bash   # custom install dir (no sudo needed there)
set -euo pipefail

# Self-update guard: the CDN edge may serve a cached copy of this script.
# The published VERSION marker names the current installer file; if it
# differs from this copy, re-fetch it (cache-busted query forces a CDN
# miss) and re-exec it.
MIRROR="https://www.tamfitronics.com/release/twcp/assets"
INSTALLER_FILE="install-curl-v4.sh"
CUR_VER="${INSTALLER_FILE#install-curl-v}"        # e.g. "4.sh" -> "4"
CUR_NUM="${CUR_VER%.sh}"                            # "4"
if [ -z "${_TWCP_INSTALL_VERSION:-}" ]; then
  if _latest="$(curl -fsSL --retry 2 "$MIRROR/VERSION?fresh=$(date +%s)" 2>/dev/null)" \
     && [ -n "$_latest" ]; then
    _LATEST_VER="${_latest#install-curl-v}"
    _LATEST_NUM="${_LATEST_VER%.sh}"
    # Only upgrade to a newer-numbered installer; never downgrade.
    if [ -n "$_LATEST_NUM" ] && [ "$_LATEST_NUM" -gt "$CUR_NUM" ]; then
      echo "Installer update available ($_latest) — re-fetching..." >&2
      _fresh_script="$(curl -fsSL "$MIRROR/$_latest?fresh=$(date +%s)")"
      exec env _TWCP_INSTALL_VERSION="$_latest" bash -c "$_fresh_script" "$@"
    fi
  fi
fi

TAG="${1:-v0.3.1}"
REPO="tbtamfit/twcp"
GITHUB="https://github.com/$REPO/releases/download/$TAG"
TARGET_DIR="${TARGET_DIR:-/usr/local/bin}"

ARCH="$(uname -m)"
case "$ARCH" in
  x86_64) GOARCH=amd64 ;;
  aarch64|arm64) GOARCH=arm64 ;;
  *) echo "Unsupported arch: $ARCH" >&2; exit 1 ;;
esac

BIN="twcp-linux-$GOARCH"
BROKER="twcp-broker-linux-$GOARCH"

if command -v sha256sum >/dev/null 2>&1; then SHA=sha256sum; else SHA=shasum -a 256; fi

TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT

# Try the public mirror first (works even though the GitHub repo is private),
# then fall back to GitHub release assets.
fetch() {
  local name="$1" dest="$2" attempt
  for attempt in 1 2 3; do
    if curl -fsSL "$MIRROR/$name" -o "$dest" 2>/dev/null && [ -s "$dest" ]; then
      return 0
    fi
    echo "Mirror attempt $attempt/3 failed for $name, retrying..." >&2
    sleep 2
  done
  echo "Mirror failed for $name, falling back to GitHub..." >&2
  curl -fsSL "$GITHUB/$name" -o "$dest"
}

echo "Installing TWCP $TAG ($GOARCH)..."
fetch "$BIN"    "$TMP/$BIN"
fetch "$BROKER" "$TMP/$BROKER"

# Verify checksums against the published SHA-256SUMS (mirror, then GitHub).
SUMS_OK=0
for src in "$MIRROR/SHA-256SUMS" "$GITHUB/SHA-256SUMS"; do
  if curl -fsSL --retry 3 "$src" -o "$TMP/SHA-256SUMS" 2>/dev/null && [ -s "$TMP/SHA-256SUMS" ]; then
    ( cd "$TMP" && grep -E " ($BIN|$BROKER)\$" SHA-256SUMS > check.sum \
      && "$SHA" -c --quiet check.sum ) && SUMS_OK=1 && break
  fi
done
if [ "$SUMS_OK" -ne 1 ]; then
  echo "WARNING: could not verify SHA-256 checksums — proceeding without them." >&2
fi

chmod +x "$TMP/$BIN" "$TMP/$BROKER"

install_one() {
  local src="$1" name="$2"
  if [ -w "$TARGET_DIR" ]; then
    install -m 0755 "$src" "$TARGET_DIR/$name"
  else
    sudo install -m 0755 "$src" "$TARGET_DIR/$name"
  fi
}

install_one "$TMP/$BIN" "twcp"
install_one "$TMP/$BROKER" "twcp-broker"

echo "Installed TWCP $TAG to $TARGET_DIR"
echo "  start panel:  twcp serve   (dashboard on :8083)"
echo "  start broker: twcp-broker"
