#!/bin/sh
# Installe la commande mini-agentic. Détecte le système, vérifie SHA-256, puis lance --version.
set -eu

SITE="${MINIAGENTIC_SITE:-https://mini-agentic.com}"
MANIFEST_URL="${MINIAGENTIC_MANIFEST_URL:-$SITE/downloads/latest.json}"

die() {
  echo "$1" >&2
  exit 1
}

command -v curl >/dev/null 2>&1 || die "curl est nécessaire pour installer Mini Agentic."
command -v tar >/dev/null 2>&1 || die "tar est nécessaire pour installer Mini Agentic."
if ! command -v sha256sum >/dev/null 2>&1 && ! command -v shasum >/dev/null 2>&1; then
  die "sha256sum ou shasum est nécessaire pour installer Mini Agentic."
fi

url_ok() {
  case "$1" in
    https://*) return 0 ;;
    http://127.0.0.1:*|http://127.0.0.1/*) return 0 ;;
    http://localhost:*|http://localhost/*) return 0 ;;
    http://[::1]:*|http://[::1]/*) return 0 ;;
    *) return 1 ;;
  esac
}

telecharger() {
  url=$1
  dest=$2
  url_ok "$url" || die "Adresse refusée."
  case "$url" in
    https://*)
      curl --fail --silent --show-error --location --proto '=https' --tlsv1.2 --retry 3 --retry-delay 1 --output "$dest" "$url"
      ;;
    *)
      curl --fail --silent --show-error --location --output "$dest" "$url"
      ;;
  esac
}

depot_ok() {
  echo "$1" | grep -Eq '^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$'
}

json_champ() {
  awk -v bloc="$2" -v champ="$3" '
    BEGIN { dedans = 0 }
    index($0, "\"" bloc "\"") > 0 { dedans = 1; next }
    dedans && index($0, "\"" champ "\"") > 0 {
      ligne = $0
      sub(/^[^:]*:[[:space:]]*"/, "", ligne)
      sub(/".*$/, "", ligne)
      print ligne
      exit
    }
    dedans && $0 ~ /^[[:space:]]*}[[:space:]]*,?[[:space:]]*$/ { exit }
  ' "$1"
}

github_repo() {
  awk '
    /"github_repo"/ {
      ligne = $0
      sub(/^[^:]*:[[:space:]]*"/, "", ligne)
      sub(/".*$/, "", ligne)
      print ligne
      exit
    }
  ' "$1"
}

empreinte() {
  if command -v sha256sum >/dev/null 2>&1; then
    sha256sum "$1" | awk '{print $1}'
  else
    shasum -a 256 "$1" | awk '{print $1}'
  fi
}

os_nom=$(uname -s)
machine=$(uname -m)
case "$os_nom" in
  Darwin) cible_os=darwin ;;
  Linux) cible_os=linux ;;
  *) die "Ce système n'est pas pris en charge." ;;
esac
case "$machine" in
  x86_64|amd64) cible_arch=x64 ;;
  arm64|aarch64) cible_arch=arm64 ;;
  *) die "Cette architecture n'est pas prise en charge." ;;
esac
cible="${cible_os}-${cible_arch}"

if [ -n "${MINIAGENTIC_INSTALL_DIR:-}" ]; then
  DEST=$MINIAGENTIC_INSTALL_DIR
elif [ "$(id -u)" -eq 0 ]; then
  DEST=/usr/local/bin
else
  DEST="${HOME}/.local/bin"
fi
mkdir -p "$DEST"

travail=$(mktemp -d)
trap 'rm -rf "$travail"' EXIT INT TERM

telecharger "$MANIFEST_URL" "$travail/site.json"
manifest="$travail/site.json"
url=$(json_champ "$manifest" "$cible" url || true)
sha=$(json_champ "$manifest" "$cible" sha256 || true)
nom=$(json_champ "$manifest" "$cible" name || true)

repo="${MINIAGENTIC_GITHUB_REPO:-}"
if [ -z "$repo" ]; then
  repo=$(github_repo "$travail/site.json" || true)
fi
if depot_ok "$repo"; then
  if curl --fail --silent --show-error --location --proto '=https' --tlsv1.2 --retry 3 --retry-delay 1 \
      --output "$travail/github.json" \
      "https://github.com/${repo}/releases/latest/download/latest.json"; then
    url_git=$(json_champ "$travail/github.json" "$cible" url || true)
    sha_git=$(json_champ "$travail/github.json" "$cible" sha256 || true)
    nom_git=$(json_champ "$travail/github.json" "$cible" name || true)
    if [ -n "$url_git" ] && [ -n "$sha_git" ]; then
      url=$url_git
      sha=$sha_git
      nom=$nom_git
    fi
  fi
fi

[ -n "$url" ] || die "Aucune version publiée pour cette machine."
url_ok "$url" || die "Adresse de téléchargement refusée."
echo "$sha" | grep -Eq '^[0-9a-fA-F]{64}$' || die "Empreinte SHA-256 absente. Installation annulée."
sha=$(printf '%s' "$sha" | tr 'A-F' 'a-f')

case "$nom" in
  mini-agentic-*-"${cible}.tar.gz") ;;
  "") nom=${url##*/} ;;
  *) die "Archive inattendue." ;;
esac
case "$nom" in
  mini-agentic-*-"${cible}.tar.gz") ;;
  *) die "Archive inattendue." ;;
esac

echo "Téléchargement de Mini Agentic (${cible})…"
telecharger "$url" "$travail/$nom"
obtenu=$(empreinte "$travail/$nom" | tr 'A-F' 'a-f')
if [ "$obtenu" != "$sha" ]; then
  die "Empreinte SHA-256 incorrecte. Installation annulée."
fi

mkdir -p "$travail/extrait"
tar -tzf "$travail/$nom" > "$travail/liste"
while IFS= read -r membre; do
  [ -n "$membre" ] || continue
  case "$membre" in
    mini-agentic|./mini-agentic) ;;
    *) die "Archive refusée." ;;
  esac
done < "$travail/liste"
tar -xzf "$travail/$nom" -C "$travail/extrait"
if [ -L "$travail/extrait/mini-agentic" ] || [ ! -f "$travail/extrait/mini-agentic" ]; then
  die "Archive refusée."
fi

cp "$travail/extrait/mini-agentic" "$DEST/mini-agentic"
chmod 755 "$DEST/mini-agentic"

if ! "$DEST/mini-agentic" --version >/dev/null; then
  die "La commande mini-agentic n'a pas pu être vérifiée."
fi

case ":$PATH:" in
  *":$DEST:"*) deja=1 ;;
  *) deja=0 ;;
esac

if [ "$deja" -eq 0 ] && [ "$DEST" = "${HOME}/.local/bin" ]; then
  shell_nom=$(basename "${SHELL:-sh}")
  if [ "$shell_nom" = "zsh" ] || [ "$os_nom" = "Darwin" ]; then
    rc="${HOME}/.zshrc"
  else
    rc="${HOME}/.bashrc"
  fi
  if [ ! -f "$rc" ] || ! grep -q "# Mini Agentic" "$rc"; then
    printf '\n# Mini Agentic\nexport PATH="%s:$PATH"\n' "$DEST" >> "$rc"
  fi
fi

echo "✓ Mini Agentic est installé."
"$DEST/mini-agentic" --version
if [ "$deja" -eq 0 ]; then
  echo "Ouvrez un nouveau terminal, puis lancez : mini-agentic"
else
  echo "Lancez : mini-agentic"
fi
