#!/usr/bin/env bash
#
# jira-remote-links.sh  -  read and write a Jira issue's Issue Links (remote links).
#
# Usage:
#   jira-remote-links.sh list  <ISSUE>              # current remote links, JSON array
#   jira-remote-links.sh apply <ISSUE> <plan.json> [--dry-run]
#
# `plan.json` is what `scripts/plan-remote-links.mjs` prints: {"write": [...], "skip": [...]}.
# `apply` POSTs each `write` entry to /rest/api/2/issue/<ISSUE>/remotelink. Jira treats a
# POST whose globalId already exists on the issue as an update, so a re-run rewrites the
# same link instead of adding a second one. This file never deletes a link: the planner
# decides what is written, and a link nobody planned stays as it is.
#
# Output of apply: one line per entry, `written <globalId>` or `failed <globalId> <http status>`,
# then `skipped <globalId> <reason>` for each skip. Exit 0 when every write succeeded, 1 when
# any failed (the rest are still attempted), 2 on a usage error, 3 when jq is missing, 4 when
# host or token did not resolve.
#
# Host and token resolve through `_jira-auth.sh`; the token reaches curl only through a -K
# config on process substitution, never argv or a log.

set -uo pipefail

usage() {
  echo "usage: jira-remote-links.sh list <ISSUE> | apply <ISSUE> <plan.json> [--dry-run]" >&2
  exit 2
}

[ $# -ge 2 ] || usage
CMD="$1"
ISSUE="$2"
[[ "$ISSUE" =~ ^[A-Z][A-Z0-9]*-[0-9]+$ ]] || { echo "jira-remote-links: not an issue key: $ISSUE" >&2; exit 2; }
command -v jq >/dev/null 2>&1 || { echo "jira-remote-links: jq not found" >&2; exit 3; }

# shellcheck source=_jira-auth.sh
. "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/_jira-auth.sh"

case "$CMD" in
  list)
    jira_auth_resolve || exit $?
    body="$(jira_api GET "/rest/api/2/issue/${ISSUE}/remotelink" -w '\n%{http_code}')"
    code="${body##*$'\n'}"
    body="${body%$'\n'*}"
    if [ "$code" != "200" ]; then
      echo "jira-remote-links: list failed for $ISSUE (HTTP $code)" >&2
      exit 1
    fi
    printf '%s' "$body" | jq -c 'if type == "array" then . else [] end' 2>/dev/null || {
      echo "jira-remote-links: list for $ISSUE did not return JSON" >&2
      exit 1
    }
    ;;
  apply)
    PLAN="${3:-}"
    [ -n "$PLAN" ] && [ -f "$PLAN" ] || usage
    DRY=0
    # A misspelled safety flag must not turn into a real write.
    case "$#:${4:-}" in
      3:) ;;
      4:--dry-run) DRY=1 ;;
      *) usage ;;
    esac
    jq -e '(.write | type) == "array"' "$PLAN" >/dev/null 2>&1 || { echo "jira-remote-links: $PLAN has no write list" >&2; exit 2; }
    # An unattended run posts nothing outside the machine; this write is no exception.
    if [ "$DRY" -eq 0 ] && [ "${MULTI_AGENT_UNATTENDED:-0}" = "1" ]; then
      jq -r '.write[]? | "skipped \(.globalId) unattended"' "$PLAN"
      exit 0
    fi
    if [ "$DRY" -eq 0 ]; then
      jira_auth_resolve || exit $?
    fi
    RC=0
    count="$(jq '.write | length' "$PLAN")"
    i=0
    while [ "$i" -lt "$count" ]; do
      entry="$(jq -c ".write[$i]" "$PLAN")"
      gid="$(printf '%s' "$entry" | jq -r '.globalId // empty')"
      i=$((i + 1))
      if [ -z "$gid" ] || [ -z "$(printf '%s' "$entry" | jq -r '.object.url // empty')" ]; then
        echo "failed ${gid:-<no-globalId>} invalid-entry"
        RC=1
        continue
      fi
      if [ "$DRY" -eq 1 ]; then
        echo "would-write $gid"
        continue
      fi
      code="$(jira_api POST "/rest/api/2/issue/${ISSUE}/remotelink" --data-binary @<(printf '%s' "$entry") -o /dev/null -w '%{http_code}')"
      case "$code" in
        200 | 201) echo "written $gid" ;;
        *) echo "failed $gid $code"; RC=1 ;;
      esac
    done
    jq -r '.skip[]? | "skipped \(.globalId) \(.reason)"' "$PLAN"
    exit "$RC"
    ;;
  *) usage ;;
esac
