#!/bin/sh
# Installs the aivopod CLI (aivopod-app docs/SPEC.md section 12) on Linux and macOS:
#   curl -fsSL https://git.belowtoxic.cloud/api/packages/aivopod/generic/aivopod-cli/latest/install.sh | sh
# Downloads the executable for this machine, checks its checksum against the .sha256 file and
# release-trust.json, and puts it to ~/.local/bin/aivopod (AIVOPOD_INSTALL_DIR). Needs neither
# Node nor Deno. AIVOPOD_VERSION picks a version, default: the newest release.
set -eu

base=${AIVOPOD_PACKAGES_URL:-https://git.belowtoxic.cloud/api/packages/aivopod/generic}
dir=${AIVOPOD_INSTALL_DIR:-$HOME/.local/bin}

case "$(uname -s)" in
  Linux) os=unknown-linux-gnu ;;
  Darwin) os=apple-darwin ;;
  *) echo "Dieses Skript ist für Linux und macOS; unter Windows install.ps1 verwenden." >&2; exit 1 ;;
esac
case "$(uname -m)" in
  x86_64 | amd64) arch=x86_64 ;;
  aarch64 | arm64) arch=aarch64 ;;
  *) echo "Nicht unterstützte Architektur: $(uname -m)" >&2; exit 1 ;;
esac
name="aivopod-$arch-$os"

sha256() {
  if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" | cut -d' ' -f1
  else shasum -a 256 "$1" | cut -d' ' -f1
  fi
}

version=${AIVOPOD_VERSION:-$(curl -fsSL "$base/aivopod-cli/latest/VERSION")}
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT

# A progress bar for the large download when someone watches (stderr is a terminal, also with
# `curl … | sh`); quiet in logs and pipelines.
if [ -t 2 ]; then progress=--progress-bar; else progress=-sS; fi

echo "[1/3] Lade aivopod $version ($name); die Datei ist groß, das kann einige Minuten dauern …"
curl -fL $progress -o "$work/$name" "$base/aivopod-cli/$version/$name"
curl -fsSL -o "$work/$name.sha256" "$base/aivopod-cli/$version/$name.sha256"
curl -fsSL -o "$work/release-trust.json" "$base/aivopod-cli/$version/release-trust.json"

echo "[2/3] Prüfe die Prüfsumme …"
expected=$(cut -d' ' -f1 < "$work/$name.sha256")
actual=$(sha256 "$work/$name")
if [ "$expected" != "$actual" ]; then
  echo "Prüfsumme stimmt nicht; abgebrochen." >&2
  exit 1
fi
if ! grep -q "\"$name\": \"sha256:$actual\"" "$work/release-trust.json"; then
  echo "Die Datei passt nicht zu release-trust.json; abgebrochen." >&2
  exit 1
fi
echo "Prüfsumme stimmt. Signatur nicht geprüft (erst ab v1 verfügbar)."

echo "[3/3] Installiere nach $dir/aivopod …"
chmod 755 "$work/$name"
# macOS: files from the internet may carry the quarantine flag; the executable is not notarized.
if [ "$os" = apple-darwin ]; then xattr -d com.apple.quarantine "$work/$name" 2>/dev/null || true; fi
mkdir -p "$dir"
mv "$work/$name" "$dir/aivopod"
echo "aivopod $version liegt in $dir/aivopod."
case ":$PATH:" in
  *":$dir:"*) ;;
  *) echo "Hinweis: $dir ist nicht im PATH. In ~/.profile ergänzen: export PATH=\"$dir:\$PATH\"" ;;
esac
echo "Weiter mit: aivopod login --url https://app.schule.example"
