#!/usr/bin/env bash
# Fetches a Gitea Actions artifact zip and installs every .deb inside.
#
# Two modes:
#   1. $ARTIFACT_URL is set → download that zip directly.
#   2. Otherwise → discover the newest successful run on $GITEA_BRANCH via the
#      `/api/v1/.../actions/tasks` endpoint and download
#      `<run.url>/artifacts/<ARTIFACT_PREFIX><head_sha>`. We use the web
#      download URL rather than `/api/v1/.../actions/artifacts`, which on this
#      Gitea instance returns an empty list even when uploads have succeeded.
set -euo pipefail

ARTIFACT_URL="${ARTIFACT_URL:-}"
ARTIFACT_PREFIX="${ARTIFACT_PREFIX:-rustdesk-server-linux-amd64-}"

work="$(mktemp -d)"
trap 'rm -rf "$work"' EXIT

if [[ -n "$ARTIFACT_URL" ]]; then
  zip_url="$ARTIFACT_URL"
  echo "==> Using pinned ARTIFACT_URL: $zip_url"
else
  : "${GITEA_URL:?GITEA_URL required when ARTIFACT_URL is unset}"
  : "${GITEA_OWNER:?GITEA_OWNER required when ARTIFACT_URL is unset}"
  : "${GITEA_REPO:?GITEA_REPO required when ARTIFACT_URL is unset}"
  : "${GITEA_BRANCH:?GITEA_BRANCH required when ARTIFACT_URL is unset}"

  api="${GITEA_URL%/}/api/v1/repos/${GITEA_OWNER}/${GITEA_REPO}"
  echo "==> Listing workflow runs at $api/actions/tasks (branch=$GITEA_BRANCH)"
  list="$(curl -fsSL "$api/actions/tasks?limit=20")"

  # Newest successful run on $GITEA_BRANCH. The .url field is the html run
  # page (e.g. .../actions/runs/173) — append /artifacts/<name> for the zip.
  read -r run_url head_sha < <(jq -r --arg branch "$GITEA_BRANCH" '
    .workflow_runs
    | map(select(.head_branch == $branch and .status == "success"))
    | sort_by(.updated_at)
    | last
    | if . == null then "" else "\(.url) \(.head_sha)" end
  ' <<<"$list")

  if [[ -z "${run_url:-}" || "$run_url" == "null" ]]; then
    echo "ERROR: no successful run on branch '$GITEA_BRANCH'." >&2
    jq -r '.workflow_runs[] | "  url=\(.url) branch=\(.head_branch) status=\(.status) updated=\(.updated_at)"' <<<"$list" >&2 || true
    exit 1
  fi

  zip_url="$run_url/artifacts/${ARTIFACT_PREFIX}${head_sha}"
  echo "==> Discovered $zip_url"
fi

echo "==> Downloading $zip_url"
curl -fsSL -o "$work/artifact.zip" "$zip_url"

mkdir -p "$work/deb"
unzip -o "$work/artifact.zip" -d "$work/deb"
mapfile -t debs < <(find "$work/deb" -type f -name '*.deb' | sort)
if [[ ${#debs[@]} -eq 0 ]]; then
  echo "ERROR: artifact zip contained no .deb files" >&2
  exit 1
fi
printf '   - %s\n' "${debs[@]}"

# Postinst scripts call deb-systemd-invoke/systemctl; block them from starting
# anything while we're inside a build layer.
echo '#!/bin/sh' >/usr/sbin/policy-rc.d
echo 'exit 101'  >>/usr/sbin/policy-rc.d
chmod +x /usr/sbin/policy-rc.d

# The .debs declare "Depends: systemd", which would drag full systemd into the
# image. The binaries themselves don't need it at runtime — only the bundled
# .service files reference it — so install with --force-depends.
dpkg -i --force-depends "${debs[@]}"

rm -f /usr/sbin/policy-rc.d
