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

server_url="${GITEA_SERVER_URL:-${GITHUB_SERVER_URL:-}}"
owner="${GITEA_REPOSITORY_OWNER:-${GITHUB_REPOSITORY_OWNER:-}}"
if [[ -z "$owner" && -n "${GITHUB_REPOSITORY:-}" && "$GITHUB_REPOSITORY" == */* ]]; then
  owner="${GITHUB_REPOSITORY%%/*}"
fi

: "${server_url:?Missing GITEA_SERVER_URL}"
: "${owner:?Missing GITEA_REPOSITORY_OWNER}"
: "${RELEASE_ASSETS_DIR:?Missing RELEASE_ASSETS_DIR}"

package_user="${RPM_PACKAGE_USERNAME:-$owner}"
token="${RPM_PACKAGE_TOKEN:-${GITEA_TOKEN:-}}"
group="${RPM_PACKAGE_GROUP:-}"

if [[ -z "$package_user" ]]; then
  echo "Missing package upload username. Set repository or organization variable RPM_PACKAGE_USERNAME." >&2
  exit 1
fi

if [[ -z "$token" ]]; then
  echo "Missing package upload token. Set RPM_PACKAGE_TOKEN or GITEA_TOKEN as a repository secret." >&2
  exit 1
fi

upload_url="${server_url%/}/api/packages/${owner}/rpm"
if [[ -n "$group" ]]; then
  upload_url="${upload_url}/${group}"
fi
upload_url="${upload_url}/upload"
upload_url="${upload_url}?sign=true"

response_file="$(mktemp)"
trap 'rm -f "$response_file"' EXIT

shopt -s nullglob
found_rpm=0
for rpm in "$RELEASE_ASSETS_DIR"/*.rpm; do
  case "$rpm" in
    *.src.rpm)
      continue
      ;;
  esac

  found_rpm=1
  package_name="$(rpm -qp --queryformat '%{NAME}' "$rpm")"
  package_version="$(rpm -qp --queryformat '%{VERSION}-%{RELEASE}' "$rpm")"
  package_arch="$(rpm -qp --queryformat '%{ARCH}' "$rpm")"

  http_code="$(
    curl --silent --show-error \
      --write-out '%{http_code}' \
      --output "$response_file" \
      --user "${package_user}:${token}" \
      --upload-file "$rpm" \
      "$upload_url"
  )"

  case "$http_code" in
    201)
      echo "Uploaded $(basename "$rpm") to the RPM package registry."
      ;;
    409)
      echo "Package already exists for $(basename "$rpm"); skipping duplicate upload."
      ;;
    *)
      echo "Failed to upload $(basename "$rpm") to $upload_url (HTTP $http_code)." >&2
      cat "$response_file" >&2 || true
      exit 1
      ;;
  esac

  package_url="${server_url%/}/api/packages/${owner}/rpm"
  if [[ -n "$group" ]]; then
    package_url="${package_url}/${group}"
  fi
  package_url="${package_url}/package/${package_name}/${package_version}/${package_arch}/${package_name}-${package_version}.${package_arch}.rpm"

  signed_rpm="$(mktemp --suffix=.rpm)"
  curl --silent --show-error --fail \
    --user "${package_user}:${token}" \
    --output "$signed_rpm" \
    "$package_url"
  mv "$signed_rpm" "$rpm"
  rpm -Kv "$rpm" || true
done
shopt -u nullglob

if [[ "$found_rpm" -ne 1 ]]; then
  echo "No binary RPM artifacts were found to upload." >&2
  exit 1
fi
