#!/bin/sh
set -eu

BIN_NAME="libreqos-test"
VERSION="${VERSION:-latest}"
BASE_URL="${BASE_URL:-https://download.libreqos.com/cli}"

# ---- Platform detection ----
OS="$(uname -s)"
ARCH="$(uname -m)"

case "$OS" in
  Linux)  PLATFORM="linux" ;;
  Darwin) PLATFORM="macos" ;;
  *)
    echo "Unsupported OS: $OS"
    exit 1
    ;;
esac

case "$ARCH" in
  x86_64|amd64) ARCH="x86_64" ;;
  aarch64|arm64) ARCH="aarch64" ;;
  *)
    echo "Unsupported architecture: $ARCH"
    exit 1
    ;;
esac

# ---- Install location ----
if [ -w "/usr/local/bin" ]; then
  DEST="/usr/local/bin"
elif [ -w "${HOME}/.local/bin" ]; then
  DEST="${HOME}/.local/bin"
else
  mkdir -p "${HOME}/.local/bin"
  DEST="${HOME}/.local/bin"
fi
mkdir -p "$DEST"

# ---- Download ----
ARCHIVE="${BIN_NAME}-${PLATFORM}-${ARCH}"
URL="${BASE_URL}/${VERSION}/${ARCHIVE}"
CHECK_URL="${URL}.sha256"

echo "Downloading ${BIN_NAME} (${PLATFORM} ${ARCH})..."
tmpdir="$(mktemp -d)"
trap 'rm -rf "$tmpdir"' EXIT

if command -v curl >/dev/null 2>&1; then
  curl -sfL "$URL" -o "${tmpdir}/${BIN_NAME}"
  curl -sfL "$CHECK_URL" -o "${tmpdir}/${BIN_NAME}.sha256"
else
  wget -q "$URL" -O "${tmpdir}/${BIN_NAME}"
  wget -q "$CHECK_URL" -O "${tmpdir}/${BIN_NAME}.sha256"
fi

# ---- Verify ----
expected="$(cut -d' ' -f1 "${tmpdir}/${BIN_NAME}.sha256")"
if command -v sha256sum >/dev/null 2>&1; then
  actual="$(sha256sum "${tmpdir}/${BIN_NAME}" | cut -d' ' -f1)"
elif command -v shasum >/dev/null 2>&1; then
  actual="$(shasum -a 256 "${tmpdir}/${BIN_NAME}" | cut -d' ' -f1)"
else
  echo "No SHA-256 utility found (need sha256sum or shasum)."
  exit 1
fi
if [ -z "$expected" ] || [ "$expected" != "$actual" ]; then
  echo "Checksum verification failed."
  exit 1
fi
echo "Checksum verified."

# ---- Install ----
chmod +x "${tmpdir}/${BIN_NAME}"
mv "${tmpdir}/${BIN_NAME}" "${DEST}/${BIN_NAME}"

echo "Installed to ${DEST}/${BIN_NAME}"
echo "Run '${BIN_NAME}' to start the bufferbloat test."
