#!/bin/sh
# Installs apcmd (aivopod-app docs/SPEC.md section 11):
#   curl -fsSL https://git.belowtoxic.cloud/api/packages/aivopod/generic/apcmd/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 /usr/local/bin/apcmd (APCMD_INSTALL_DIR; sudo if needed).
# APCMD_VERSION picks a version, default: the newest release.
set -eu

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

case "$(uname -s)" in
  Linux) ;;
  *) echo "apcmd läuft nur unter Linux." >&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="apcmd-$arch-unknown-linux-gnu"

version=${APCMD_VERSION:-$(curl -fsSL "$base/apcmd/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 apcmd $version ($name) …"
curl -fL $progress -o "$work/$name" "$base/apcmd/$version/$name"
curl -fsSL -o "$work/$name.sha256" "$base/apcmd/$version/$name.sha256"
curl -fsSL -o "$work/release-trust.json" "$base/apcmd/$version/release-trust.json"

echo "[2/3] Prüfe die Prüfsumme …"
expected=$(cut -d' ' -f1 < "$work/$name.sha256")
actual=$(sha256sum "$work/$name" | cut -d' ' -f1)
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/apcmd …"
chmod 755 "$work/$name"
if [ -w "$dir" ]; then
  mv "$work/$name" "$dir/apcmd"
else
  sudo mv "$work/$name" "$dir/apcmd"
fi
echo "apcmd $version liegt in $dir/apcmd. Weiter mit: sudo apcmd install"
