#!/bin/bash
# Rebuild APT repository index after adding/updating packages
# Run this after dropping a new .deb into pool/
set -euo pipefail

REPO_ROOT="/var/www/apt.praxisec.com"
GPG_EMAIL="packages@praxisec.com"

cd "$REPO_ROOT"

echo "Scanning packages..."

# Generate Packages file for amd64
dpkg-scanpackages --arch amd64 pool/ > dists/stable/main/binary-amd64/Packages
gzip -9c dists/stable/main/binary-amd64/Packages > dists/stable/main/binary-amd64/Packages.gz

# Generate Packages file for arm64 (future Raspberry Pi support)
dpkg-scanpackages --arch arm64 pool/ > dists/stable/main/binary-arm64/Packages 2>/dev/null || true
gzip -9c dists/stable/main/binary-arm64/Packages > dists/stable/main/binary-arm64/Packages.gz 2>/dev/null || true

# Count packages
PKG_COUNT=$(grep -c "^Package:" dists/stable/main/binary-amd64/Packages 2>/dev/null || echo "0")

# Generate Release file
cat > dists/stable/Release << RELEOF
Origin: PraxiSec
Label: PraxiSec RF Toolkit
Suite: stable
Codename: stable
Version: 1.0
Architectures: amd64 arm64
Components: main
Description: PraxiSec RF Toolkit packages
Date: $(date -Ru)
RELEOF

# Add checksums to Release
{
    echo "MD5Sum:"
    for f in dists/stable/main/binary-amd64/Packages dists/stable/main/binary-amd64/Packages.gz; do
        if [ -f "$f" ]; then
            size=$(stat -c%s "$f")
            md5=$(md5sum "$f" | cut -d' ' -f1)
            rel_path=${f#dists/stable/}
            printf " %s %d %s\n" "$md5" "$size" "$rel_path"
        fi
    done
    echo "SHA256:"
    for f in dists/stable/main/binary-amd64/Packages dists/stable/main/binary-amd64/Packages.gz; do
        if [ -f "$f" ]; then
            size=$(stat -c%s "$f")
            sha=$(sha256sum "$f" | cut -d' ' -f1)
            rel_path=${f#dists/stable/}
            printf " %s %d %s\n" "$sha" "$size" "$rel_path"
        fi
    done
} >> dists/stable/Release

# Sign the Release file
rm -f dists/stable/Release.gpg dists/stable/InRelease
gpg --default-key "$GPG_EMAIL" -abs -o dists/stable/Release.gpg dists/stable/Release
gpg --default-key "$GPG_EMAIL" --clearsign -o dists/stable/InRelease dists/stable/Release

echo "Repository rebuilt: $PKG_COUNT package(s)"
echo "  Packages: dists/stable/main/binary-amd64/Packages"
echo "  Release:  dists/stable/Release (signed)"
