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

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

# Libraries
LIBDIR=/usr/lib
source "$LIBDIR/setup/bash/logging.sh"

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

PACKAGE_TYPE="$1"; shift

# Verify given type + associate with config
case "$PACKAGE_TYPE" in
	deb)
		declare -n PACKAGE_UPLOADS=DEB_URLS
		;;
	rpm)
		declare -n PACKAGE_UPLOADS=RPM_URLS
		;;
	*)
		error "Invalid format '$FORMAT'. Supported ones are 'deb' and 'rpm'."
		;;
esac

PACKAGE_PATHS=("$@")
if [[ "${#PACKAGE_PATHS[@]}" -eq 0 ]]; then
	error "No packages path provided"
fi
# Verify all paths, cancel all uploads
for package in "${PACKAGE_PATHS[@]}"; do
	if [[ ! -f "$package" ]]; then
		error "$package is not a valid file."
	fi
	if [[ "$package" != *.$PACKAGE_TYPE ]]; then
		error "$package is not a $PACKAGE_TYPE package"
	fi
done

# Loop on each given package
for upload_url in "${PACKAGE_UPLOADS}"; do
	line
	log "Publishing to $upload_url..."
	line

	for package in "${PACKAGE_PATHS[@]}"; do
		log "  $(basename "$package")"
		curl --fail --silent --show-error \
			--user "$FORGEJO_USER:$FORGEJO_TOKEN" \
			--upload-file "$package" \
			"$FORGEJO_URL/api/packages/$FORGEJO_USER/$upload_url/upload"
	done
done
