#!/usr/bin/env bash
# Fail closed before deployment if the live upload bucket cannot accept the
# browser's conditional, checksum-bound PUT preflight.
set -euo pipefail

BUCKET="${1:?Usage: check-upload-cors.sh <bucket> <web-origin> [region]}"
WEB_ORIGIN="${2:?Usage: check-upload-cors.sh <bucket> <web-origin> [region]}"
REGION="${3:-ap-southeast-1}"
URL="https://${BUCKET}.s3.${REGION}.amazonaws.com/helix-cors-preflight"
HEADERS_FILE=$(mktemp)
trap 'rm -f "$HEADERS_FILE"' EXIT

STATUS=$(curl --silent --show-error --output /dev/null \
  --dump-header "$HEADERS_FILE" --write-out '%{http_code}' \
  --request OPTIONS "$URL" \
  --header "Origin: ${WEB_ORIGIN}" \
  --header 'Access-Control-Request-Method: PUT' \
  --header 'Access-Control-Request-Headers: content-type,if-none-match,x-amz-checksum-sha256')

if [[ "$STATUS" != "200" ]]; then
  echo "ERROR: upload bucket CORS preflight returned HTTP ${STATUS}; refusing deployment." >&2
  exit 1
fi

header_value() {
  local wanted="$1"
  awk -v wanted="$wanted" '
    index(tolower($0), tolower(wanted) ":") == 1 {
      sub(/^[^:]*:[[:space:]]*/, "")
      sub(/\r$/, "")
      print
      exit
    }
  ' "$HEADERS_FILE"
}

ALLOW_ORIGIN=$(header_value 'access-control-allow-origin')
ALLOW_METHODS=$(header_value 'access-control-allow-methods' | tr '[:lower:]' '[:upper:]')
ALLOW_HEADERS=$(header_value 'access-control-allow-headers' | tr '[:upper:]' '[:lower:]')

if [[ "$ALLOW_ORIGIN" != "$WEB_ORIGIN" ]]; then
  echo "ERROR: upload bucket CORS does not allow exact origin ${WEB_ORIGIN}; refusing deployment." >&2
  exit 1
fi
if [[ ",${ALLOW_METHODS// /}," != *",PUT,"* ]]; then
  echo "ERROR: upload bucket CORS does not allow PUT; refusing deployment." >&2
  exit 1
fi
for required in content-type if-none-match x-amz-checksum-sha256; do
  if [[ ",${ALLOW_HEADERS// /}," != *",${required},"* ]]; then
    echo "ERROR: upload bucket CORS does not allow ${required}; refusing deployment." >&2
    exit 1
  fi
done

echo "Upload bucket CORS preflight passed for ${WEB_ORIGIN}."
