#!/bin/sh
# srht-build -- submit a sr.ht build manifest and follow output
set -eu

MANIFEST="${1:-.build.yml}"

if [ ! -f "$MANIFEST" ]; then
    echo "No manifest found: $MANIFEST" >&2
    exit 1
fi

if command -v hut >/dev/null 2>&1; then
    exec hut builds submit -f "$MANIFEST"
fi

# Fallback to curl
TOKEN=$(cat ~/.config/srht/token)
CONTENT=$(python3 -c "import sys,json; print(json.dumps(sys.stdin.read()))" < "$MANIFEST")

RESULT=$(curl -s --oauth2-bearer "$TOKEN" -H 'Content-Type: application/json' \
  -d "{\"query\": \"mutation(\$m: String!) { submit(manifest: \$m) { id status } }\", \"variables\": {\"manifest\": $CONTENT}}" \
  https://builds.sr.ht/query)

JOB_ID=$(echo "$RESULT" | jq -r '.data.submit.id')
echo "[+] Submitted: https://builds.sr.ht/~krisyotam/job/$JOB_ID"
