#!/usr/bin/env bash
#
# This script will publish a package to a Gitea Composer package repository.
# Developed as part of NoccyLabs workflows, Copyright 2025 NoccyLabs
# Licensed under GPL 2.0 or later.
#
# Arguments:
#   server - The domain component of the Gitea server hosting the repository
#   owner  - The owner of the package repository on the Gitea instance
#   auth   - Credentials, in the form user:token
#
# _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

if [ -z $3 ]; then
  echo "Usage: $0 <giteadomain> <owner> <user:token>" 1>&2
  exit 1
fi

# grab arguments
server=$1
owner=$2
auth=$3

# determine package name (from composer.json) and version (from git tag)
pct_package="$(cat composer.json | jq -r .name)"
pct_version="$(git describe --tags)"
pct_filename="$(echo "$pct_package" | sed 's/\//-/')--$pct_version.zip"

# make sure the package's composer.json contains the version key
jq ".version = \"$tag\"" composer.json > composer.json~ &&
    mv composer.json~ composer.json

# create the zip archiev from the files in the repository
git ls-files | xargs zip "$pct_filename"

# and push it to Gitea
curl --user $auth \
     --upload-file "$pct_filename" \
     "https://$server/api/packages/$owner/composer?version=$pct_version"

