#!/usr/bin/env bash
set -euo pipefail

# fetch-sha256.sh - Fetch and compute SRI hash for OpenCode release
#
# Usage: fetch-sha256.sh <version>
#
# Example: fetch-sha256.sh 1.0.58
# Output: sha256-ABC123... (SRI format)

# Check arguments
if [[ $# -ne 1 ]]; then
  echo "Error: Missing required argument" >&2
  echo "Usage: $0 <version>" >&2
  echo "Example: $0 1.0.58" >&2
  exit 1
fi

VERSION="$1"

# Validate version format (X.Y.Z)
if ! echo "$VERSION" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+$'; then
  echo "Error: Invalid version format '$VERSION' (expected X.Y.Z)" >&2
  exit 1
fi

# Check dependencies
for cmd in nix-prefetch-url nix; do
  if ! command -v "$cmd" >/dev/null 2>&1; then
    echo "Error: Required command '$cmd' not found" >&2
    exit 1
  fi
done

# Construct download URL
URL="https://github.com/sst/opencode/releases/download/v${VERSION}/opencode-linux-x64.zip"

# Fetch file and compute Nix base-32 hash
# Note: nix-prefetch-url outputs hash to stdout, potential warnings/info to stderr
# Allow nix-prefetch-url to fail gracefully so we can provide a custom error message
NIX_HASH=$(nix-prefetch-url --type sha256 "$URL" 2>/dev/null | head -1 || true)

if [[ -z "$NIX_HASH" ]]; then
  echo "Error: Failed to fetch or hash $URL" >&2
  echo "       Verify version $VERSION exists on GitHub releases" >&2
  exit 1
fi

# Convert Nix base-32 hash to SRI format (sha256-...)
SRI_HASH=$(nix hash to-sri --type sha256 "$NIX_HASH" 2>/dev/null)

if [[ -z "$SRI_HASH" ]]; then
  echo "Error: Failed to convert hash to SRI format" >&2
  exit 1
fi

# Validate SRI hash format
if ! echo "$SRI_HASH" | grep -qE '^sha256-[A-Za-z0-9+/]+=*$'; then
  echo "Error: Generated hash '$SRI_HASH' does not match SRI format" >&2
  exit 1
fi

# Output SRI hash
echo "$SRI_HASH"
