#!/bin/sh
# Cowth CLI installer for Linux
# Usage: curl -fsSL https://download.cowth.dev/install.sh | sh
set -eu

COWTH_VERSION="${COWTH_VERSION:-latest}"
DOWNLOAD_BASE="https://download.cowth.dev"
INSTALL_DIR="${COWTH_INSTALL_DIR:-/usr/local/bin}"

# resolve "latest" to a real version
if [ "$COWTH_VERSION" = "latest" ]; then
  COWTH_VERSION="$(curl -fsSL "${DOWNLOAD_BASE}/latest-version.txt")"
fi

# detect architecture
ARCH="$(uname -m)"
case "$ARCH" in
  x86_64)  PLATFORM="linux-x64" ;;
  aarch64) PLATFORM="linux-arm64" ;;
  *)
    echo "Unsupported architecture: $ARCH" >&2
    echo "Download a binary manually from ${DOWNLOAD_BASE}" >&2
    exit 1
    ;;
esac

ARTIFACT_BASE="cowthctl-${COWTH_VERSION}-${PLATFORM}"
ZIP_NAME="${ARTIFACT_BASE}.zip"
ZIP_URL="${DOWNLOAD_BASE}/${ZIP_NAME}"
SUMS_URL="${DOWNLOAD_BASE}/SHA256SUMS-${COWTH_VERSION}.txt"

TMP_DIR="$(mktemp -d)"
cleanup() { rm -rf "$TMP_DIR"; }
trap cleanup EXIT

echo "Downloading cowthctl ${COWTH_VERSION} (${PLATFORM})..."
curl -fsSL "$ZIP_URL" -o "$TMP_DIR/${ZIP_NAME}"
curl -fsSL "$SUMS_URL" -o "$TMP_DIR/SHA256SUMS.txt"

echo "Verifying checksum..."
(
  cd "$TMP_DIR"
  grep "${ZIP_NAME}" SHA256SUMS.txt | sha256sum -c
)

unzip -q "$TMP_DIR/${ZIP_NAME}" -d "$TMP_DIR"
chmod +x "$TMP_DIR/${ARTIFACT_BASE}/cowthctl"

if [ -w "$INSTALL_DIR" ]; then
  cp "$TMP_DIR/${ARTIFACT_BASE}/cowthctl" "$INSTALL_DIR/cowthctl"
else
  sudo cp "$TMP_DIR/${ARTIFACT_BASE}/cowthctl" "$INSTALL_DIR/cowthctl"
fi

echo ""
echo "Installed: $INSTALL_DIR/cowthctl"
echo "Version:   $(cowthctl --version)"
echo ""
echo "Get started: cowthctl --help"
