#!/bin/sh
# Repair the official installer repository policy without changing packages.
# Parse the complete repair before executing when downloaded through a pipe.
repair_mom_repos() {
set -eu
TARGET=${1:-/}
case "$TARGET" in /*) ;; *) echo "target root must be absolute" >&2; exit 2;; esac
REPOS=$TARGET/etc/mom/repos.d
KEY=$TARGET/etc/mom/keys/ekkobsd-21-mom.pub
[ -f "$KEY" ] || { echo "installed MOM public key is missing: $KEY" >&2; exit 1; }
grep -q '100121fe2c4575f9c09d504ffe4573d0faf4455eeb7bcb1151f28f2a84cf0903' "$KEY" || {
 echo "installed key is not the official ekkoBSD 2.1 MOM key" >&2; exit 1;
}
mkdir -p "$REPOS"
# Preserve existing configuration outside repos.d so MOM cannot load the backup.
BACKUP=$(mktemp -d "$TARGET/etc/mom/repositories-before-r2.XXXXXXXX")
for name in ekkobsd-release ekkobsd-r2; do
 if [ -e "$REPOS/$name.toml" ]; then
  [ ! -L "$REPOS/$name.toml" ] || { echo "refusing symlinked repository configuration" >&2; exit 1; }
  cp -p "$REPOS/$name.toml" "$BACKUP/$name.toml"
 fi
done
STAGE=$(mktemp -d "$REPOS/.r2-policy.XXXXXXXX")
trap 'rm -rf "$STAGE"' EXIT HUP INT TERM
cat > "$STAGE/ekkobsd-r2.toml" <<'CONFIG'
name = "ekkobsd-r2"
url = "https://cdn.ekkobsd.org/pub/ekkoBSD/releases/2.1/{arch}/packages"
key = "ekkobsd-21-mom.pub"
priority = 100
enabled = true
CONFIG
cat > "$STAGE/ekkobsd-release.toml" <<'CONFIG'
name = "ekkobsd-release"
url = "file:///mnt2/2.1/{arch}/mom"
key = "ekkobsd-21-mom.pub"
priority = -100
enabled = true
CONFIG
chmod 0644 "$STAGE/"*.toml
# Install R2 first so an interrupted repair never leaves a media-only root.
mv -f "$STAGE/ekkobsd-r2.toml" "$REPOS/ekkobsd-r2.toml"
mv -f "$STAGE/ekkobsd-release.toml" "$REPOS/ekkobsd-release.toml"
printf 'R2 is primary; installation CD mounted at /mnt2 is lower-priority fallback.\nBackup: %s\n' "$BACKUP"
}
repair_mom_repos "$@"
