#!/bin/bash
# Delete an attachment from a Jira issue by attachment id

set -e

# Arguments
ATTACHMENT_ID="$1"

# Validation
if [ -z "$ATTACHMENT_ID" ]; then
    echo "Error: Missing attachment id" >&2
    echo "Usage: $0 <attachment-id>" >&2
    echo "" >&2
    echo "Example: $0 10231" >&2
    echo "Attachment ids are listed in get-issue.sh output under fields.attachment[].id" >&2
    exit 1
fi

# Check environment variables
if [ -z "$ATLASSIAN_SITE_NAME" ] || [ -z "$ATLASSIAN_USER_EMAIL" ] || [ -z "$ATLASSIAN_API_TOKEN" ]; then
    echo "Error: Jira environment variables not set" >&2
    exit 1
fi

# Delete attachment. Success is HTTP 204 with no body.
STATUS=$(curl -s -o /dev/null -w '%{http_code}' -X DELETE \
    -u "${ATLASSIAN_USER_EMAIL}:${ATLASSIAN_API_TOKEN}" \
    "${ATLASSIAN_SITE_NAME}/rest/api/2/attachment/${ATTACHMENT_ID}")

if [ "$STATUS" != "204" ]; then
    echo "Error: delete failed with HTTP ${STATUS}" >&2
    exit 1
fi

echo '{"success": true, "deleted_attachment": "'"$ATTACHMENT_ID"'"}'
