#!/bin/zsh
#MISE description="Upload to Codeberg packages"
#USAGE flag "-v --verbose" help="enable verbose logging"
#USAGE flag "-d --dist <dir>" env="PACKAGE_DIST" default="target/dist" help="specify location of distribution directory"
#USAGE flag "-n --dry-run" help="don't actually upload"
#USAGE flag "--version <ver>" help="Override package version"
#USAGE flag "--bindist <path>" env="MDBIN_PATH" default="bindist" help="path to bindist tools within root"

ZSL_USAGE=1
. stdlib.zsh || exit 2

ACT=1
if [[ $usage_dry_run ]]; then
	msg "enabling dry run"
	ACT=0
fi

: ${FORGE_URL:=https://codeberg.org}

if [[ -z $FORGE_USER ]]; then
	die "no FORGE_USER, cannot upload"
fi
if [[ -z $FORGE_TOKEN ]]; then
	die "no FORGE_TOKEN, cannot upload"
fi

API_URL="$FORGE_URL/api/v1/packages/$FORGE_USER/generic"
PKG_URL="$FORGE_URL/api/packages/$FORGE_USER/generic"

msg -dbg "ensuring we have package info"
. "${usage_bindist}/pkg-info.sh" || die "cannot load package info"

if [[ $usage_version ]]; then
	PACKAGE_VERSION="$usage_version"
fi

msg "preparing to upload $PACKAGE_NAME $PACKAGE_VERSION from ${usage_dist}"

msg "querying for existing versions"
declare -a EXISTING=()
EXISTING=($(
	curl -fs --user "$FORGE_USER:$FORGE_TOKEN" -H "accept: application/json" \
		"$API_URL/$PACKAGE_NAME/$PACKAGE_VERSION/files" |
		jq -r '.[].name'
))
ps=("${pipestatus[@]}")
if ((${ps[1]})); then
	msg "package info not available, assuming new upload"
elif ((${ps[2]})); then
	die "failed to parse JSON response"
else
	msg "found ${#EXISTING[@]} already-uploaded files"
fi

setopt null_glob
N=0
for file in "${usage_dist}/${PACKAGE_NAME}-${PACKAGE_VERSION}"-*.tgz; do
	name="$(basename "$file")"
	upload=1
	for fn in "$EXISTING[@]"; do
		if [[ $fn = $name ]]; then
			msg -warn "$name already uploaded, skipping"
			upload=0
			break
		fi
	done
	if (($upload)); then
		if (($ACT)); then
			msg -action "uploading $name"
			curl -fs --user "$FORGE_USER:$FORGE_TOKEN" --upload-file "$file" \
				"$PKG_URL/$PACKAGE_NAME/$PACKAGE_VERSION/$name"
			if (($?)); then
				die "failed to upload $name"
			fi
		else
			msg "would upload $name, disabled for dry run"
		fi
		N=$(($N + 1))
	fi
done

msg -success "uploaded $N packages"
