#!/usr/bin/env bash
# Upload the built [tanin] packages to the Gitea Arch registry.
# Run after build-tanin-repo.sh / finish-tanin-repo.sh produced the .pkg.tar.zst.
# Needs a Gitea token with the `write:package` scope:
#   TANIN_PKG_TOKEN=xxxx ./publish-tanin-repo.sh     (or it will prompt)
# Gitea builds the repo DB server-side; nothing else to upload.
set -uo pipefail
OUT="${TANIN_REPO_DIR:-$HOME/projects/tanin-repo}"
OWNER="${TANIN_OWNER:-karim}"
DISTRO="${TANIN_DISTRO:-tanin}"
BASE="https://git.openbureau.ch/api/packages/$OWNER/arch/$DISTRO"

TOK="${TANIN_PKG_TOKEN:-}"
[ -z "$TOK" ] && { read -rsp "Gitea token (write:package): " TOK; echo; }
[ -z "$TOK" ] && { echo "no token"; exit 1; }

shopt -s nullglob
n=0
for f in "$OUT"/*.pkg.tar.zst; do
  case "$f" in *-debug-*) continue;; esac   # skip debug symbol packages
  code=$(curl -s -o /dev/null -w '%{http_code}' --user "$OWNER:$TOK" \
    --upload-file "$f" "$BASE")
  echo "$code  $(basename "$f")"
  [ "$code" = 201 ] && n=$((n+1))
done
echo "uploaded $n package(s) to $BASE"
echo "verify: curl -s $BASE/x86_64/tanin.db | gzip -dc | tar tf - | sed -n 's#/desc\$##p'"
