#!/usr/bin/env bash
# Upload dist/ release files to the GitLab Generic Package Registry and attach
# them to the GitLab Release so downloads do not depend on job-artifact
# permalinks (those 404 when the latest tag pipeline is failed or still running).
#
# Usage:
#   publish-gitlab-release.sh [--dry-run] [--dist DIR] [tag]
#
# In CI, tag defaults to $CI_COMMIT_TAG. Dry-run prints the upload/link plan
# and does not call the GitLab API.
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
DIST="$ROOT/dist"
DRY_RUN=0
TAG="${CI_COMMIT_TAG:-}"

usage() {
  echo "Usage: $0 [--dry-run] [--dist DIR] [tag]" >&2
  exit 2
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --dry-run) DRY_RUN=1; shift ;;
    --dist)
      [[ $# -ge 2 ]] || usage
      DIST="$2"
      shift 2
      ;;
    -h|--help) usage ;;
    *)
      if [[ -n "$TAG" && "$TAG" != "$1" ]]; then
        echo "Unexpected argument: $1" >&2
        usage
      fi
      TAG="$1"
      shift
      ;;
  esac
done

if [[ -z "$TAG" ]]; then
  TAG="$(grep '^version = ' "$ROOT/Cargo.toml" | sed -E 's/.*"([^"]+)"/\1/')"
fi
VERSION="${TAG#v}"

is_debug_pkg() {
  local base
  base="$(basename -- "$1")"
  [[ "$base" == posprint-debug-* || "$base" == *-debug-*.pkg.tar.zst ]]
}

# Prints: label<TAB>absolute-path
collect_assets() {
  local f
  shopt -s nullglob
  local debs=("$DIST"/*.deb)
  local pkgs=("$DIST"/posprint-*-x86_64.pkg.tar.zst)
  local tgzs=("$DIST"/posprint-*-x86_64.tar.gz)
  shopt -u nullglob

  if [[ ${#debs[@]} -ne 1 ]]; then
    echo "Expected exactly one .deb in $DIST, found ${#debs[@]}" >&2
    ls -la "$DIST" >&2 || true
    return 1
  fi
  printf '%s\t%s\n' "Linux .deb (amd64)" "${debs[0]}"

  local main_pkg=""
  for f in "${pkgs[@]+"${pkgs[@]}"}"; do
    if ! is_debug_pkg "$f"; then
      if [[ -n "$main_pkg" ]]; then
        echo "Multiple non-debug Arch packages in $DIST" >&2
        return 1
      fi
      main_pkg="$f"
    fi
  done
  if [[ -z "$main_pkg" ]]; then
    echo "No non-debug Arch .pkg.tar.zst in $DIST" >&2
    ls -la "$DIST" >&2 || true
    return 1
  fi
  printf '%s\t%s\n' "Arch Linux .pkg.tar.zst (x86_64)" "$main_pkg"

  if [[ ${#tgzs[@]} -ne 1 ]]; then
    echo "Expected exactly one posprint-*-x86_64.tar.gz in $DIST, found ${#tgzs[@]}" >&2
    ls -la "$DIST" >&2 || true
    return 1
  fi
  printf '%s\t%s\n' "Linux binary tarball (x86_64, AUR posprint-bin)" "${tgzs[0]}"

  if [[ ! -f "$DIST/posprint.exe" ]]; then
    echo "Missing $DIST/posprint.exe" >&2
    ls -la "$DIST" >&2 || true
    return 1
  fi
  printf '%s\t%s\n' "Windows .exe" "$DIST/posprint.exe"
}

json_escape() {
  printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g'
}

generic_file_url() {
  local name="$1"
  printf '%s/projects/%s/packages/generic/posprint/%s/%s' \
    "${CI_API_V4_URL}" "${CI_PROJECT_ID}" "${VERSION}" "${name}"
}

ASSETS="$(collect_assets)"

if [[ "$DRY_RUN" -eq 1 ]]; then
  echo "tag=${TAG}"
  echo "version=${VERSION}"
  echo "dist=${DIST}"
  while IFS=$'\t' read -r label path; do
    name="$(basename -- "$path")"
    printf 'UPLOAD\t%s\t%s\t%s\n' "$label" "$path" "$name"
    printf 'LINK\t%s\t/%s\n' "$label" "$name"
  done <<<"$ASSETS"
  exit 0
fi

: "${CI_JOB_TOKEN:?CI_JOB_TOKEN is required to publish a GitLab release}"
: "${CI_API_V4_URL:?CI_API_V4_URL is required to publish a GitLab release}"
: "${CI_PROJECT_ID:?CI_PROJECT_ID is required to publish a GitLab release}"

api() {
  local method="$1"
  local path="$2"
  local body_file="${3:-}"
  local out_file="$4"
  local extra=()
  if [[ -n "$body_file" ]]; then
    extra+=(--header "Content-Type: application/json" --data @"$body_file")
  fi
  curl -sS -X "$method" \
    --header "JOB-TOKEN: ${CI_JOB_TOKEN}" \
    "${extra[@]}" \
    -o "$out_file" -w "%{http_code}" \
    "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}${path}"
}

upload_generic() {
  local file="$1"
  local name
  name="$(basename -- "$file")"
  local url
  url="$(generic_file_url "$name")"
  local tmp code
  tmp="$(mktemp)"
  code="$(curl -sS -o "$tmp" -w "%{http_code}" \
    --header "JOB-TOKEN: ${CI_JOB_TOKEN}" \
    --upload-file "$file" \
    "$url")"
  if [[ "$code" == "201" || "$code" == "200" ]]; then
    echo "Uploaded $name ($code)"
    rm -f "$tmp"
    return 0
  fi
  if [[ "$code" == "400" || "$code" == "409" ]] && grep -qiE 'already|exist|duplicate|taken|cannot be reused' "$tmp"; then
    echo "Already uploaded $name (ok)"
    rm -f "$tmp"
    return 0
  fi
  echo "Upload failed for $name ($code): $(cat "$tmp")" >&2
  rm -f "$tmp"
  return 1
}

echo "Publishing GitLab release ${TAG} from ${DIST}"

while IFS=$'\t' read -r _label path; do
  upload_generic "$path"
done <<<"$ASSETS"

LINKS_JSON=""
first=1
while IFS=$'\t' read -r label path; do
  name="$(basename -- "$path")"
  url="$(generic_file_url "$name")"
  item="$(printf '{"name":"%s","url":"%s","link_type":"package","direct_asset_path":"/%s"}' \
    "$(json_escape "$label")" \
    "$(json_escape "$url")" \
    "$(json_escape "$name")")"
  if [[ "$first" -eq 1 ]]; then
    LINKS_JSON="$item"
    first=0
  else
    LINKS_JSON="${LINKS_JSON},${item}"
  fi
done <<<"$ASSETS"

DESC="Cross-platform POS print designer release ${TAG}"
CREATE_BODY="$(mktemp)"
RESP="$(mktemp)"
trap 'rm -f "$CREATE_BODY" "$RESP"' EXIT

cat >"$CREATE_BODY" <<EOF
{"name":"posprint ${TAG}","tag_name":"${TAG}","description":"$(json_escape "$DESC")","assets":{"links":[${LINKS_JSON}]}}
EOF

code="$(api GET "/releases/${TAG}" "" "$RESP")"
if [[ "$code" == "404" ]]; then
  code="$(api POST "/releases" "$CREATE_BODY" "$RESP")"
  if [[ "$code" != "201" && "$code" != "200" ]]; then
    echo "Failed to create release ($code): $(cat "$RESP")" >&2
    exit 1
  fi
  echo "Created GitLab release ${TAG}"
  exit 0
fi

if [[ "$code" != "200" ]]; then
  echo "Failed to query release ${TAG} ($code): $(cat "$RESP")" >&2
  exit 1
fi

UPDATE_BODY="$(mktemp)"
cat >"$UPDATE_BODY" <<EOF
{"name":"posprint ${TAG}","description":"$(json_escape "$DESC")"}
EOF
code="$(api PUT "/releases/${TAG}" "$UPDATE_BODY" "$RESP")"
rm -f "$UPDATE_BODY"
if [[ "$code" != "200" ]]; then
  echo "Failed to update release ${TAG} ($code): $(cat "$RESP")" >&2
  exit 1
fi

# Replace existing asset links so retries pick up new filenames/URLs.
code="$(api GET "/releases/${TAG}/assets/links" "" "$RESP")"
if [[ "$code" == "200" ]]; then
  if command -v jq >/dev/null; then
    mapfile -t LINK_IDS < <(jq -r '.[].id // empty' "$RESP" || true)
  else
    mapfile -t LINK_IDS < <(grep -oE '"id":[0-9]+' "$RESP" | sed 's/"id"://' || true)
  fi
  for link_id in "${LINK_IDS[@]+"${LINK_IDS[@]}"}"; do
    [[ -n "$link_id" ]] || continue
    del_code="$(api DELETE "/releases/${TAG}/assets/links/${link_id}" "" "$RESP")"
    if [[ "$del_code" != "204" && "$del_code" != "200" ]]; then
      echo "Warning: could not delete release link ${link_id} ($del_code): $(cat "$RESP")" >&2
    fi
  done
fi

while IFS=$'\t' read -r label path; do
  name="$(basename -- "$path")"
  url="$(generic_file_url "$name")"
  link_body="$(mktemp)"
  cat >"$link_body" <<EOF
{"name":"$(json_escape "$label")","url":"$(json_escape "$url")","link_type":"package","direct_asset_path":"/$(json_escape "$name")"}
EOF
  code="$(api POST "/releases/${TAG}/assets/links" "$link_body" "$RESP")"
  rm -f "$link_body"
  if [[ "$code" != "201" && "$code" != "200" ]]; then
    echo "Failed to add release link ${name} ($code): $(cat "$RESP")" >&2
    exit 1
  fi
done <<<"$ASSETS"

echo "Updated GitLab release ${TAG} with Generic Package Registry assets"
