#!/usr/bin/env bash
set -euo pipefail

REPO=/var/www/repo.mizodevelopment.com/termux
SUITE=stable
KEYID=17314A9D3D886166

# Build Packages index for aarch64
DPKG_SCAN=$(command -v dpkg-scanpackages)
if [ -z "$DPKG_SCAN" ]; then
  echo "dpkg-scanpackages not found" >&2
  exit 1
fi

mkdir -p "$REPO/dists/$SUITE/main/binary-aarch64"

(
  cd "$REPO"
  $DPKG_SCAN -a aarch64 "pool/main" /dev/null \
    > "$REPO/dists/$SUITE/main/binary-aarch64/Packages"
)
gzip -kf "$REPO/dists/$SUITE/main/binary-aarch64/Packages"

# Release metadata
RELEASE_TMP=$(mktemp)
apt-ftparchive release "$REPO/dists/$SUITE" > "$RELEASE_TMP"
cat > "$REPO/dists/$SUITE/Release" <<EOF
Origin: Mizo Development
Label: Mizo
Suite: $SUITE
Codename: $SUITE
Architectures: aarch64
Components: main
Description: Mizo Termux Repo
$(cat "$RELEASE_TMP")
EOF
rm -f "$RELEASE_TMP"

# Sign (non-interactive)
GPG_ARGS=(--batch --yes --pinentry-mode loopback --passphrase '' --default-key "$KEYID")

gpg "${GPG_ARGS[@]}" --clearsign \
  -o "$REPO/dists/$SUITE/InRelease" "$REPO/dists/$SUITE/Release"
gpg "${GPG_ARGS[@]}" -abs \
  -o "$REPO/dists/$SUITE/Release.gpg" "$REPO/dists/$SUITE/Release"

echo "Repo updated: $REPO"
