#!/usr/bin/env bash
# Downloads every attachment listed on a fetched Jira issue JSON file into a resources
# directory. Filenames are preserved as-is; on a name collision the attachment id is
# prefixed to keep both files.
#
# Usage: jira-download-attachments.sh <ISSUE-JSON-PATH> <RESOURCES-DIR>
#
# On success, prints one TSV line per downloaded file to stdout:
#   <relative-filename>\t<mimeType>\t<bytes>
#
# Requires: JIRA_CREDENTIALS (same as jira-fetch-issue.sh)

set -euo pipefail

usage() {
  echo "Usage: $(basename "$0") <ISSUE-JSON-PATH> <RESOURCES-DIR>" >&2
  exit 1
}

[ $# -eq 2 ] || usage

ISSUE_JSON="$1"
RESOURCES_DIR="$2"

[ -f "$ISSUE_JSON" ] || { echo "No such file: $ISSUE_JSON" >&2; exit 1; }

if [ -z "${JIRA_CREDENTIALS:-}" ]; then
  echo "JIRA_CREDENTIALS is not set." >&2
  exit 1
fi

command -v curl >/dev/null 2>&1 || { echo "curl is required" >&2; exit 1; }
command -v jq >/dev/null 2>&1 || { echo "jq is required" >&2; exit 1; }

mkdir -p "$RESOURCES_DIR"
AUTH="$(printf '%s' "$JIRA_CREDENTIALS" | base64 -w0)"

COUNT="$(jq '(.fields.attachment // []) | length' "$ISSUE_JSON")"
if [ "$COUNT" -eq 0 ]; then
  exit 0
fi

for i in $(seq 0 $((COUNT - 1))); do
  ID="$(jq -r ".fields.attachment[$i].id" "$ISSUE_JSON")"
  NAME="$(jq -r ".fields.attachment[$i].filename" "$ISSUE_JSON")"
  MIME="$(jq -r ".fields.attachment[$i].mimeType // \"application/octet-stream\"" "$ISSUE_JSON")"
  URL="$(jq -r ".fields.attachment[$i].content" "$ISSUE_JSON")"

  DEST_NAME="$NAME"
  if [ -e "${RESOURCES_DIR}/${DEST_NAME}" ]; then
    DEST_NAME="${ID}-${NAME}"
  fi
  DEST="${RESOURCES_DIR}/${DEST_NAME}"

  HTTP_STATUS="$(curl -sS -L -o "$DEST" -w '%{http_code}' \
    -H "Authorization: Basic ${AUTH}" \
    "$URL")"

  if [ "$HTTP_STATUS" != "200" ]; then
    echo "Failed to download attachment ${ID} (${NAME}): HTTP ${HTTP_STATUS}" >&2
    rm -f "$DEST"
    continue
  fi

  BYTES="$(wc -c < "$DEST" | tr -d ' ')"
  printf '%s\t%s\t%s\n' "$DEST_NAME" "$MIME" "$BYTES"
done
