#!/usr/bin/env bash
set -Eeuo pipefail
umask 077

config_dir="${XDG_CONFIG_HOME:-$HOME/.config}/hermes-stack-maintenance"
runner="$(dirname -- "${BASH_SOURCE[0]}")/hermes-stack-llama-run"

case "${1:-list}" in
  list)
    printf '%-12s %8s %10s\n' Profil Kontext Fit-MiB \
      baseline 65536 1536 vram-64k 65536 1280 \
      balanced 49152 1536 vram-plus 49152 1280 compact 32768 1536
    exit 0 ;;
  baseline|vram-64k|balanced|vram-plus|compact) selected="$1" ;;
  *)
    printf 'Unbekanntes Profil. Verfügbare Profile: %s list\n' "$0" >&2
    exit 2 ;;
esac
[[ $# -eq 1 ]] || exit 2

exec 9>"${XDG_RUNTIME_DIR:-/tmp}/hermes-stack-hermes-update.lock"
flock -n 9 || {
  printf 'Maintenance läuft; nichts geändert.\n' >&2
  exit 1
}

# shellcheck disable=SC1090
source "$config_dir/llama.env"
[[ -n "${LLAMA_PROFILE:-}" ]] || {
  printf 'Profilbetrieb ist nicht konfiguriert.\n' >&2
  exit 1
}

"$runner" --profile "$selected" --check

target="$config_dir/llama-profile.env"
[[ ! -L "$target" ]] || {
  printf 'Abbruch: Profilwahl ist ein Symlink.\n' >&2
  exit 1
}

if [[ -e "$target" ]]; then
  [[ -f "$target" ]] || exit 1
  backup="$(mktemp "$config_dir/llama-profile.backup.XXXXXX")"
  cp -p -- "$target" "$backup"
  printf 'Vorherige Profilwahl gesichert: %s\n' "$backup"
fi

candidate="$(mktemp "$config_dir/llama-profile.env.pending.XXXXXX")"
trap 'rm -f -- "$candidate"' EXIT
printf 'LLAMA_PROFILE=%q\n' "$selected" >"$candidate"
mv -T -- "$candidate" "$target"

printf 'Profil %s für den nächsten Dienststart gespeichert. Kein Neustart.\n' "$selected"
