#!/usr/bin/env bash
# -----------------------------------------------------------------------------
# build-repo.sh  –  regenerate minimal Debian/apt repository
# -----------------------------------------------------------------------------
# 1. copies the current custom-theme.deb from ../ClockworkPi-pi-gen/custom-theme/
#    (edit PKG_SRC below if your path is different)
# 2. puts it into pool/main/c/clockworkpi-theme/
# 3. runs dpkg-scanpackages to create Packages & Packages.gz
# 4. writes a small Release stub (not signed – fine for private use, add gpg
#    signing later if you wish)
#
# After running, commit & push this repo – the raw URLs will be usable as an
# apt source on any machine.
# -----------------------------------------------------------------------------
set -euo pipefail

PKG_SRC="../ClockworkPi-pi-gen/custom-theme/custom-theme.deb"   # location of .deb
POOL_DIR="pool/main/c/clockworkpi-theme"
DIST="bookworm"
COMP="stable"
ARCH="all"

if [[ ! -f "${PKG_SRC}" ]]; then
  echo "ERROR: ${PKG_SRC} not found – build your theme package first." >&2
  exit 1
fi

mkdir -p "${POOL_DIR}"
cp -u "${PKG_SRC}" "${POOL_DIR}/"  # copy only if newer (keeps history)

BIN_DIR="dists/${DIST}/${COMP}/main/binary-${ARCH}"
mkdir -p "${BIN_DIR}"

# Generate Packages & Packages.gz
if ! command -v dpkg-scanpackages >/dev/null; then
  echo "ERROR: dpkg-scanpackages not found – install dpkg-dev." >&2
  exit 1
fi

dpkg-scanpackages --arch "${ARCH}" pool /dev/null > "${BIN_DIR}/Packages"
 gzip -9c "${BIN_DIR}/Packages" > "${BIN_DIR}/Packages.gz"

# Minimal Release file (unsigned)
mkdir -p "dists/${DIST}"
cat > "dists/${DIST}/Release" <<EOF
Origin: Custom
Label: Custom Repo
Suite: ${COMP}
Version: 1.0
Codename: ${DIST}
Architectures: ${ARCH}
Components: main
Description: Personal ClockworkPi repository
EOF

echo "Repository updated – commit & push."