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

# MIDAS CLI installer
#   curl -fsSL https://get.trymidas.io | bash

APP=midas
BASE_URL="${MIDAS_INSTALL_BASE:-https://get.trymidas.io}"
INSTALL_DIR="${MIDAS_INSTALL_DIR:-$HOME/.midas/bin}"

BOLD='\033[1m'
DIM='\033[0;2m'
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[0;33m'
NC='\033[0m'

err() { echo -e "${RED}error:${NC} $*" >&2; exit 1; }
info() { echo -e "${DIM}$*${NC}"; }

command -v curl >/dev/null 2>&1 || err "curl is required but not installed."

raw_os=$(uname -s | tr '[:upper:]' '[:lower:]')
case "$raw_os" in
  darwin) os=darwin ;;
  linux)  os=linux ;;
  msys*|mingw*|cygwin*|windows*) err "Windows uses install.ps1 instead: irm https://get.trymidas.io/install.ps1 | iex" ;;
  *) err "unsupported OS: $raw_os" ;;
esac

raw_arch=$(uname -m)
case "$raw_arch" in
  arm64|aarch64) arch=arm64 ;;
  x86_64|amd64)  arch=x64 ;;
  *) err "unsupported architecture: $raw_arch" ;;
esac

target="${APP}-${os}-${arch}"
url="${BASE_URL}/bin/${target}?t=$(date +%s)"

echo -e "${BOLD}Installing MIDAS CLI${NC} ${DIM}(${os}-${arch})${NC}"

mkdir -p "$INSTALL_DIR"

# Cache-bust: the distribution edge honors object Cache-Control and can otherwise
# serve a stale VERSION or binary for up to an hour.
# In-app updates pass the requested version through VERSION; fall back to the
# bucket's published version for fresh installs.
version="${VERSION:-$(curl -fsSL "${BASE_URL}/VERSION?t=$(date +%s)" 2>/dev/null || true)}"
[ -n "$version" ] && info "version ${version}"

# Stage the download next to the target so the final swap is an atomic rename on
# the same filesystem. A crash mid-download leaves the working binary untouched.
tmp="$(mktemp "${INSTALL_DIR}/.${APP}.download.XXXXXX")"
sums="$(mktemp)"
trap 'rm -f "$tmp" "$sums" "$sums.sig"' EXIT

# Sweep staging files abandoned by an interrupted run (older than an hour).
find "$INSTALL_DIR" -maxdepth 1 -name ".${APP}.download.*" -mmin +60 -delete 2>/dev/null || true

info "downloading ${url}"
if ! curl -fSL --proto '=https' --tlsv1.2 -o "$tmp" "$url"; then
  err "download failed. No build for ${target} yet — ask for it to be published."
fi

# A truncated or HTML error page is not a Mach-O/ELF binary; guard against it.
if [ ! -s "$tmp" ]; then
  err "downloaded file is empty."
fi

# Integrity (mandatory): verify the staged binary against the SHA256SUMS manifest
# published beside the binaries. This stops a truncated download, a wrong-arch
# build, or a swapped object from replacing a working install.
sums_url="${BASE_URL}/SHA256SUMS?t=$(date +%s)"
if ! curl -fSL --proto '=https' --tlsv1.2 -o "$sums" "$sums_url"; then
  err "no integrity manifest at ${sums_url}; refusing to install an unverified binary."
fi
expected="$(awk -v n="${target}" '$2 == n || $2 == "*" n { print $1; exit }' "$sums")"
[ -n "$expected" ] || err "SHA256SUMS has no entry for ${target}; refusing to install."
if command -v shasum >/dev/null 2>&1; then
  actual="$(shasum -a 256 "$tmp" | awk '{ print $1 }')"
else
  actual="$(sha256sum "$tmp" | awk '{ print $1 }')"
fi
[ "$actual" = "$expected" ] || err "checksum mismatch for ${target} (expected ${expected}, got ${actual}); refusing to install."

# Optional signature: when a minisign public key is configured, the manifest must
# also carry a valid detached signature. Inert until that key is wired in.
if [ -n "${MIDAS_MINISIGN_PUBKEY:-}" ]; then
  command -v minisign >/dev/null 2>&1 || err "minisign is required to verify this build but is not installed."
  if ! curl -fsSL --proto '=https' --tlsv1.2 -o "$sums.sig" "${BASE_URL}/SHA256SUMS.minisig?t=$(date +%s)"; then
    err "signature required but ${BASE_URL}/SHA256SUMS.minisig is missing."
  fi
  minisign -Vm "$sums" -x "$sums.sig" -P "${MIDAS_MINISIGN_PUBKEY}" >/dev/null 2>&1 \
    || err "SHA256SUMS signature verification failed; refusing to install."
fi

info "checksum verified"
chmod 755 "$tmp"

# On an in-app update, verify the staged binary actually runs and reports the
# expected version before letting it replace a working install. Fresh installs
# skip this so a first-time download is never blocked by a version mismatch.
if [ -n "${VERSION:-}" ] && [ -n "$version" ]; then
  got="$("$tmp" --version 2>/dev/null || true)"
  case "$got" in
    *"$version"*) : ;;
    *) err "downloaded binary failed verification (expected ${version}, got ${got:-no output})" ;;
  esac
fi

mv -f "$tmp" "$INSTALL_DIR/${APP}"
chmod 755 "$INSTALL_DIR/${APP}"
trap - EXIT

echo -e "${GREEN}installed${NC} ${INSTALL_DIR}/${APP}"

# ---- ensure INSTALL_DIR is on PATH ----------------------------------------
add_path_line="export PATH=\"${INSTALL_DIR}:\$PATH\""
marker="# midas cli"

already_on_path=false
case ":$PATH:" in
  *":${INSTALL_DIR}:"*) already_on_path=true ;;
esac

rc=""
case "${SHELL:-}" in
  */zsh)  rc="$HOME/.zshrc" ;;
  */bash) if [ "$os" = darwin ]; then rc="$HOME/.bash_profile"; else rc="$HOME/.bashrc"; fi ;;
esac

if [ "$already_on_path" = true ]; then
  : # nothing to do
elif [ -n "$rc" ]; then
  if [ -f "$rc" ] && grep -qF "$marker" "$rc"; then
    :
  else
    printf '\n%s\n%s\n' "$marker" "$add_path_line" >> "$rc"
    info "added ${INSTALL_DIR} to PATH in ${rc}"
  fi
  needs_reload=true
else
  echo -e "${YELLOW}note:${NC} add this to your shell config to put midas on PATH:"
  echo -e "  ${add_path_line}"
fi

echo ""
echo -e "${BOLD}Done.${NC} Next steps:"
if [ "${needs_reload:-false}" = true ] && [ "$already_on_path" != true ]; then
  echo -e "  1. Restart your terminal (or run: ${BOLD}source ${rc}${NC})"
  echo -e "  2. Run ${BOLD}midas${NC}"
else
  echo -e "  1. Run ${BOLD}midas${NC}"
fi
echo -e "  ${DIM}·${NC} Inside midas, type ${BOLD}/login${NC} to connect your MIDAS account."
echo -e "  ${DIM}·${NC} MIDAS routes your work across models automatically — just start coding."
