#!/usr/bin/env bash
# Downloads and unpacks a specific version of the MockServer CLI bundle.
# Called by asdf/mise with ASDF_INSTALL_VERSION and ASDF_DOWNLOAD_PATH set.
#
# MockServer ships as a self-contained bundle (its own trimmed Java runtime +
# a `bin/mockserver` launcher), archived per platform as
#   mockserver-<version>-<os>-<arch>.tar.gz   (.zip for windows)
# on the GitHub Release "mockserver-<version>". This script downloads the
# matching archive and extracts its contents into ASDF_DOWNLOAD_PATH.

set -euo pipefail

if [[ -z "${ASDF_INSTALL_VERSION:-}" ]]; then
  echo "ASDF_INSTALL_VERSION is required" >&2
  exit 1
fi

if [[ -z "${ASDF_DOWNLOAD_PATH:-}" ]]; then
  echo "ASDF_DOWNLOAD_PATH is required" >&2
  exit 1
fi

# Detect platform and architecture, mapping to the bundle naming convention.
get_os() {
  case "$(uname -s | tr '[:upper:]' '[:lower:]')" in
    linux)  echo "linux" ;;
    darwin) echo "darwin" ;;
    mingw*|msys*|cygwin*) echo "windows" ;;
    *) echo "Unsupported OS: $(uname -s)" >&2; exit 1 ;;
  esac
}

get_arch() {
  case "$(uname -m)" in
    x86_64|amd64)  echo "x86_64" ;;
    aarch64|arm64) echo "aarch64" ;;
    *) echo "Unsupported architecture: $(uname -m)" >&2; exit 1 ;;
  esac
}

os="$(get_os)"
arch="$(get_arch)"
version="$ASDF_INSTALL_VERSION"

ext="tar.gz"
[[ "$os" == "windows" ]] && ext="zip"

archive="mockserver-${version}-${os}-${arch}.${ext}"
url="https://github.com/mock-server/mockserver-monorepo/releases/download/mockserver-${version}/${archive}"

echo "Downloading MockServer CLI ${version} for ${os}-${arch}..."
mkdir -p "$ASDF_DOWNLOAD_PATH"

archive_path="$ASDF_DOWNLOAD_PATH/$archive"
if ! curl -fsSL -o "$archive_path" "$url"; then
  echo "Failed to download MockServer CLI from: $url" >&2
  echo "Check that version ${version} publishes a bundle for ${os}-${arch}" >&2
  exit 1
fi

# Verify the archive against its published .sha256 sidecar before extracting,
# so a corrupted or tampered download is rejected. The sidecar is the same
# `<hash>  <filename>` format the release publishes for every platform bundle.
if ! curl -fsSL -o "$archive_path.sha256" "${url}.sha256"; then
  echo "Failed to download checksum sidecar: ${url}.sha256" >&2
  exit 1
fi
echo "Verifying checksum..."
(
  cd "$ASDF_DOWNLOAD_PATH"
  if command -v sha256sum >/dev/null 2>&1; then
    sha256sum -c "$archive.sha256"
  else
    shasum -a 256 -c "$archive.sha256"
  fi
) || { echo "Checksum verification failed for $archive" >&2; exit 1; }
rm -f "$archive_path.sha256"

# Extract the archive, then hoist the single top directory
# (mockserver-<version>-<os>-<arch>/) so bin/, lib/ and runtime/ live directly
# under ASDF_DOWNLOAD_PATH for the install step.
extract_root="$ASDF_DOWNLOAD_PATH/.extract"
rm -rf "$extract_root"
mkdir -p "$extract_root"
if [[ "$ext" == "zip" ]]; then
  unzip -q "$archive_path" -d "$extract_root"
else
  tar -xzf "$archive_path" -C "$extract_root"
fi

top_dir="$extract_root/mockserver-${version}-${os}-${arch}"
if [[ ! -d "$top_dir" ]]; then
  # Fall back to whatever single directory the archive expanded to.
  top_dir="$(find "$extract_root" -mindepth 1 -maxdepth 1 -type d | head -n1)"
fi
[[ -d "$top_dir" ]] || { echo "Unexpected archive layout in $archive" >&2; exit 1; }

cp -R "$top_dir/." "$ASDF_DOWNLOAD_PATH/"
rm -rf "$extract_root" "$archive_path"
