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

# Config
source /etc/setup/forgejo/publish.conf

# Libraries
source /usr/lib/setup/bash/logging.sh

DEB_DIR="${1:-.}";

FORGEJO_TOKEN="${FORGEJO_TOKEN:?FORGEJO_TOKEN env variable is required. Export it before running the command}"

if [[ $# -gt 0 ]]; then
	error "Usage: forgejo-publish-deb <path-to-deb-directory>"
fi

if [[ ! -d $DEB_DIR ]]; then
	error "$DEB_DIR is not a directory"
fi

DEB_FILES=("$DEB_DIR"/*.deb)
if [[ ! -e "${DEB_FILES[0]}" ]]; then
	error "No .deb files found in $DEB_DIR"
fi

for dist in "${!DISTRIBUTIONS[@]}"; do
	component="${DISTRIBUTIONS[$dist]}"
	line
	log "Publishing to $dist/$component..."
	line

	for deb in "${DEB_FILES[@]}"; do
		log "  $(basename "$deb")"
		curl --fail --silent --show-error \
			--user "$FORGEJO_USER:$FORGEJO_TOKEN" \
			--upload-file "$deb" \
			"$FORGEJO_URL/api/packages/$FORGEJO_USER/debian/pool/$dist/$component/upload"
	done
done
