#!/usr/bin/env bash
# Download a Jira issue's image attachments so they can be read and inspected.
#
# Usage: download_attachments.sh <issueKey> <outDir> [maxBytes]
#
# The useful evidence in a support ticket is often a screenshot, not the text:
# the actual screen, the actual error, the actual values.
#
# Downloads only image/* attachments, skipping anything larger than maxBytes
# (default 10 MB). Prints one "<path>  <filename>  <bytes>" line per file.
# Pass an output directory OUTSIDE the repository: screenshots may contain
# personal data (references/pii.md).
#
# Reads JIRA_BASE_URL / JIRA_EMAIL / JIRA_API_TOKEN through load_env.sh.
# Requires: curl, python3 (or python).
set -euo pipefail

KEY="${1:?Usage: download_attachments.sh <issueKey> <outDir> [maxBytes]}"
OUT_DIR="${2:?Usage: download_attachments.sh <issueKey> <outDir> [maxBytes]}"
MAX_BYTES="${3:-10485760}"

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=load_env.sh
source "$HERE/load_env.sh"
require_jira

if [[ ! "$KEY" =~ ^[A-Za-z][A-Za-z0-9_]+-[0-9]+$ ]]; then
  echo "ERROR: '$KEY' is not a full Jira key (expected PROJ-1234)" >&2
  exit 1
fi

BASE="$JIRA_BASE_URL"
AUTH="$JIRA_EMAIL:$JIRA_API_TOKEN"
PY="$(command -v python3 || command -v python || true)"
[[ -n "$PY" ]] || { echo "ERROR: python3 is required" >&2; exit 1; }
export PYTHONIOENCODING=utf-8

mkdir -p "$OUT_DIR"

manifest="$(curl -sf -u "$AUTH" -H "Accept: application/json" \
  "$BASE/rest/api/2/issue/$KEY?fields=attachment" 2>/dev/null || true)"
if [[ -z "$manifest" ]]; then
  echo "ERROR: could not read attachments of $KEY (bad key or credentials)" >&2
  exit 1
fi

# "filename<TAB>url" for image attachments within the size limit.
rows="$(printf '%s' "$manifest" | MAXB="$MAX_BYTES" "$PY" -c "
import sys, json, os
maxb = int(os.environ['MAXB'])
d = json.load(sys.stdin)
for a in (d.get('fields') or {}).get('attachment') or []:
    if not (a.get('mimeType') or '').startswith('image/'):
        continue
    if (a.get('size') or 0) > maxb:
        sys.stderr.write('skipped (too large): %s\n' % a.get('filename'))
        continue
    name = (a.get('filename') or 'attachment').replace('\t', '_').replace('/', '_')
    print('%s\t%s' % (name, a.get('content') or ''))
" | tr -d '\r')"
# tr -d '\r': python prints CRLF on Windows and a trailing \r breaks the URL.

if [[ -z "$rows" ]]; then
  echo "(no image attachments in $KEY)"
  exit 0
fi

# Rows on fd 3: curl would otherwise read (and swallow) the loop's stdin.
while IFS=$'\t' read -r name url <&3; do
  [[ -z "$name" || -z "$url" ]] && continue
  dest="$OUT_DIR/${KEY}_${name}"
  if curl -sfL -u "$AUTH" "$url" -o "$dest" </dev/null; then
    size="$(wc -c < "$dest" | tr -d ' ')"
    echo "$dest  $name  ${size}b"
  else
    echo "WARN: failed to download $name" >&2
  fi
done 3<<< "$rows"
