#!/bin/bash
set -eu

BASE_URL="https://blossom.laantungir.net"
PRIVKEY="22cc83aa57928a2800234c939240c9a6f0f44a33ea3838a860ed38930b195afd"
FILE="/tmp/ginxsom_browser_sample.html"

cat > "$FILE" <<'EOF'
<!doctype html>
<html>
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <title>Ginxsom Browser Sample</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 2rem; background: #0b1020; color: #e6e9f2; }
    .card { max-width: 720px; padding: 1.25rem 1.5rem; border: 1px solid #2a3350; border-radius: 12px; background: #121a33; }
    code { background: #1b2545; padding: 0.1rem 0.35rem; border-radius: 6px; }
    .ok { color: #69f0ae; }
  </style>
</head>
<body>
  <div class="card">
    <h1>Ginxsom HTML test</h1>
    <p class="ok">If you can see this page, remote HTML upload and retrieval are working.</p>
    <p>Timestamp: <code id="ts"></code></p>
  </div>
  <script>
    document.getElementById("ts").textContent = new Date().toISOString();
  </script>
</body>
</html>
EOF

SHA=$(sha256sum "$FILE" | cut -d' ' -f1)
EXP=$(date -d '+1 hour' +%s)
EVENT=$(nak event -k 24242 -c "" --sec "$PRIVKEY" -t "t=upload" -t "x=$SHA" -t "expiration=$EXP")
AUTH="Nostr $(echo -n "$EVENT" | base64 -w 0)"
RESP=$(mktemp)

STATUS=$(curl -s -w "%{http_code}" -o "$RESP" \
  -X PUT \
  -H "Authorization: $AUTH" \
  -H "Content-Type: text/html" \
  --data-binary "@$FILE" \
  "$BASE_URL/upload")

URL=$(jq -r '.url // empty' "$RESP")
GET_CODE=0
if [ -n "$URL" ]; then
  GET_CODE=$(curl -s -o /dev/null -w "%{http_code}" "$URL")
fi

echo "UPLOAD_STATUS=$STATUS"
echo "SHA256=$SHA"
echo "URL=$URL"
echo "GET_CODE=$GET_CODE"
