#!/bin/sh
set -eu

download_root="https://isorek.com/downloads/Isorek-MCP"
latest_url="$download_root/latest.txt"

fail() {
  printf 'Isorek MCP install: %s\n' "$1" >&2
  exit 1
}

command -v curl >/dev/null 2>&1 || fail "curl is required."

operating_system="$(uname -s)"
architecture="$(uname -m)"
case "$operating_system/$architecture" in
  Darwin/arm64|Darwin/x86_64)
    platform="macOS-universal"
    archive_extension="zip"
    command -v unzip >/dev/null 2>&1 || fail "unzip is required."
    ;;
  Linux/x86_64|Linux/amd64)
    if [ -n "${WSL_DISTRO_NAME:-}" ] || grep -qi microsoft /proc/version 2>/dev/null; then
      fail "WSL is not supported in 0.1. Install the Windows binary from native PowerShell instead."
    fi
    platform="Linux-x86_64"
    archive_extension="tar.gz"
    ;;
  Darwin/*)
    fail "Unsupported Mac architecture: $architecture."
    ;;
  Linux/*)
    fail "Linux 0.1 supports x86_64 only; detected $architecture."
    ;;
  *)
    fail "Unsupported platform: $operating_system/$architecture. On Windows, run the PowerShell installer."
    ;;
esac

version="${ISOREK_MCP_VERSION:-}"
if [ -z "$version" ]; then
  version="$(curl --proto '=https' --tlsv1.2 -fsSL "$latest_url" | tr -d '\r\n ')"
fi
printf '%s\n' "$version" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+([+-][0-9A-Za-z.-]+)?$' || fail "The published version is invalid: $version"

archive_name="Isorek-MCP-$version-$platform.$archive_extension"
version_root="$download_root/$version"
temporary_directory="$(mktemp -d "${TMPDIR:-/tmp}/isorek-mcp.XXXXXX")"
archive_path="$temporary_directory/$archive_name"
checksums_path="$temporary_directory/SHA256SUMS"
cleanup() {
  rm -rf "$temporary_directory"
}
trap cleanup EXIT HUP INT TERM

printf 'Downloading Isorek MCP %s for %s...\n' "$version" "$platform"
curl --proto '=https' --tlsv1.2 -fsSL "$version_root/$archive_name" -o "$archive_path"
curl --proto '=https' --tlsv1.2 -fsSL "$version_root/SHA256SUMS" -o "$checksums_path"

expected_checksum="$(awk -v archive="$archive_name" '$2 == archive || $2 == "*" archive { print tolower($1); exit }' "$checksums_path")"
[ -n "$expected_checksum" ] || fail "SHA256SUMS does not contain $archive_name."
if command -v shasum >/dev/null 2>&1; then
  actual_checksum="$(shasum -a 256 "$archive_path" | awk '{ print tolower($1) }')"
elif command -v sha256sum >/dev/null 2>&1; then
  actual_checksum="$(sha256sum "$archive_path" | awk '{ print tolower($1) }')"
else
  fail "shasum or sha256sum is required to verify the download."
fi
if [ "$actual_checksum" != "$expected_checksum" ]; then
  printf 'Warning: the release archive did not match the checksum manifest. Retrying both without cache...\n' >&2
  cache_bust="$(date +%s)-$$"
  curl --proto '=https' --tlsv1.2 -fsSL -H 'Cache-Control: no-cache' "$version_root/$archive_name?isorekRetry=$cache_bust" -o "$archive_path"
  curl --proto '=https' --tlsv1.2 -fsSL -H 'Cache-Control: no-cache' "$version_root/SHA256SUMS?isorekRetry=$cache_bust" -o "$checksums_path"

  expected_checksum="$(awk -v archive="$archive_name" '$2 == archive || $2 == "*" archive { print tolower($1); exit }' "$checksums_path")"
  [ -n "$expected_checksum" ] || fail "SHA256SUMS does not contain $archive_name after a fresh retry."
  if command -v shasum >/dev/null 2>&1; then
    actual_checksum="$(shasum -a 256 "$archive_path" | awk '{ print tolower($1) }')"
  else
    actual_checksum="$(sha256sum "$archive_path" | awk '{ print tolower($1) }')"
  fi
  [ "$actual_checksum" = "$expected_checksum" ] || fail "SHA-256 verification failed for $archive_name after a fresh retry (expected $expected_checksum, got $actual_checksum)."
fi

case "$archive_extension" in
  zip)
    unzip -q "$archive_path" -d "$temporary_directory"
    ;;
  tar.gz)
    tar -xzf "$archive_path" -C "$temporary_directory"
    ;;
esac

package_directory="$temporary_directory/Isorek-MCP-$version-$platform"
source_binary="$package_directory/isorek-mcp"
[ -f "$source_binary" ] || fail "The archive does not contain the expected isorek-mcp binary."

if [ "$operating_system" = "Darwin" ]; then
  codesign --verify --strict --check-notarization --verbose=2 "$source_binary" || fail "The macOS code signature or notarization is invalid."
fi

install_directory="$HOME/.local/bin"
install_path="$install_directory/isorek-mcp"
staged_install_path="$install_path.new.$$"
mkdir -p "$install_directory"
install -m 755 "$source_binary" "$staged_install_path"
mv -f "$staged_install_path" "$install_path"

if [ "$operating_system" = "Darwin" ]; then
  codesign --verify --strict "$install_path" || fail "The installed macOS code signature is invalid."
fi

printf '\nInstalled Isorek MCP %s\n' "$version"
printf 'Binary: %s\n\n' "$install_path"
case ":${PATH:-}:" in
  *":$install_directory:"*) ;;
  *)
    printf 'The install directory is not on PATH in this shell. Run:\n'
    printf '  export PATH="%s:$PATH"\n\n' "$install_directory"
    ;;
esac
printf 'Detected clients:\n'
if ! "$install_path" clients add --detected; then
  printf '\nThe binary was installed, but one or more client registrations need attention.\n' >&2
  printf 'Run: %s clients\n' "$install_path" >&2
fi

printf '\nManage clients: %s clients\n' "$install_path"
printf 'Diagnostics:    %s doctor\n' "$install_path"
printf 'Restart configured clients, then ask:\n'
printf '“List my open Isorek plugin instances, read their JSON, and ask me which IDs to edit.”\n'
