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

DATA_DIR="/var/lib/debrepo"
CONF_DIR="/etc/debrepo"

usage() {
    echo "Usage: $0 <codename> <deb-file>"
    echo ""
    echo "Add a .deb package to the repository for the given distribution."
    echo ""
    echo "Codenames: bullseye bookworm trixie sid focal jammy noble oracular"
    echo ""
    echo "Example: $0 bookworm /tmp/myapp_1.2.3_amd64.deb"
    exit 1
}

if [ $# -ne 2 ]; then
    usage
fi

codename="$1"
deb_file="$2"

if [ ! -f "$deb_file" ]; then
    echo "Error: file not found: $deb_file" >&2
    exit 1
fi

valid_codenames="bullseye bookworm trixie sid focal jammy noble oracular"
if ! echo "$valid_codenames" | grep -qw "$codename"; then
    echo "Error: unknown codename: $codename" >&2
    echo "Valid codenames: $valid_codenames" >&2
    exit 1
fi

# --- Allowlist check ---
ALLOWED_PACKAGES="$CONF_DIR/allowed-packages"
if [ -f "$ALLOWED_PACKAGES" ]; then
    # Count non-blank, non-comment lines
    entry_count=$(grep -cvE '^\s*($|#)' "$ALLOWED_PACKAGES" || true)
    if [ "$entry_count" -gt 0 ]; then
        pkg_name=$(dpkg-deb -f "$deb_file" Package)
        if ! grep -vE '^\s*($|#)' "$ALLOWED_PACKAGES" | grep -qxF "$pkg_name"; then
            echo "Error: package '$pkg_name' is not in the allowlist ($ALLOWED_PACKAGES)" >&2
            exit 1
        fi
    fi
fi

reprepro --confdir "$CONF_DIR" -b "$DATA_DIR" includedeb "$codename" "$deb_file"
echo "Successfully added $(basename "$deb_file") to $codename"
