#!/usr/bin/env bash
# Publish dist/pool as a static apt tree (NAROS.md §3.2): dist/repo/dists/<channel>/main/
# with per-arch Packages(.xz) and a signed InRelease when a key is available.
#
#   publish.sh [--channel edge|stable] [--sign KEYID]
#
# Unsigned mode is for local/dev use only (consume with [trusted=yes]); CI always signs
# (key from the NAROS_APT_SIGNING_KEY secret). Sync to R2 is r2-sync.sh's job.
set -euo pipefail

OS_DIR="$(cd "$(dirname "$0")/.." && pwd)"
CHANNEL="${NAROS_CHANNEL:-edge}" KEYID="${NAROS_APT_KEYID:-}"
while [ $# -gt 0 ]; do
  case "$1" in
    --channel) CHANNEL="$2"; shift 2 ;;
    --sign) KEYID="$2"; shift 2 ;;
    *) echo "unknown arg: $1" >&2; exit 2 ;;
  esac
done

POOL="$OS_DIR/dist/pool"
REPO="$OS_DIR/dist/repo"
DISTS="$REPO/dists/$CHANNEL/main"
[ -d "$POOL" ] || { echo "no pool at $POOL — run packages/build-all.sh first" >&2; exit 2; }

rm -rf "$REPO/dists/$CHANNEL"
mkdir -p "$REPO/pool/main"
cp -a "$POOL/." "$REPO/pool/main/" 2>/dev/null || true
rm -f "$REPO/pool/main/Packages"

cd "$REPO"
for arch in arm64 amd64; do
  bindir="dists/$CHANNEL/main/binary-$arch"
  mkdir -p "$bindir"
  # Arch-specific debs for this arch + arch:all debs, one Packages per binary-<arch>.
  dpkg-scanpackages --multiversion --arch "$arch" pool > "$bindir/Packages"
  xz -k -f "$bindir/Packages"
done

apt-ftparchive \
  -o "APT::FTPArchive::Release::Origin=narOS" \
  -o "APT::FTPArchive::Release::Label=narOS" \
  -o "APT::FTPArchive::Release::Suite=$CHANNEL" \
  -o "APT::FTPArchive::Release::Codename=$CHANNEL" \
  -o "APT::FTPArchive::Release::Architectures=arm64 amd64" \
  -o "APT::FTPArchive::Release::Components=main" \
  release "dists/$CHANNEL" > "dists/$CHANNEL/Release"

if [ -n "$KEYID" ]; then
  gpg --batch --yes -u "$KEYID" --clearsign -o "dists/$CHANNEL/InRelease" "dists/$CHANNEL/Release"
  gpg --batch --yes -u "$KEYID" --detach-sign --armor -o "dists/$CHANNEL/Release.gpg" "dists/$CHANNEL/Release"
  echo "published SIGNED repo: $REPO (channel $CHANNEL, key $KEYID)"
else
  echo "published UNSIGNED repo: $REPO (channel $CHANNEL) — dev only, consume with [trusted=yes]"
fi
