#!/bin/bash

source ./.env

# Auto-detect DAR file from ../dars/
if [ -d "../dars" ]; then
  AUTO_DAR_FILE=$(find ../dars -name "*.dar" -type f | head -1)
  if [ -n "$AUTO_DAR_FILE" ]; then
    DAR_FILE="$AUTO_DAR_FILE"
    echo "🔍 Auto-detected DAR file: $DAR_FILE"
  fi
fi

echo "Uploading DAR file: $DAR_FILE"
echo "Endpoint: $PARTICIPANT_API_ENDPOINT/v2/packages"
echo ""

CANTON_TOKEN=$(cd ../config && ./get_token.sh)

response=$(curl -X POST $PARTICIPANT_API_ENDPOINT/v2/packages \
    --fail-with-body \
    -sS \
    -H "Authorization: Bearer $CANTON_TOKEN" \
    -H "Content-Type: application/octet-stream" \
    --data-binary @$DAR_FILE)

curl_exit_code=$?

if [ $curl_exit_code -eq 0 ]; then
    echo "✅ Upload successful!"
    echo "Response:"
    echo "$response" | jq '.' 2>/dev/null || echo "$response"
else
    echo "❌ Upload failed with exit code: $curl_exit_code"
    echo "Error response:"
    echo "$response" | jq '.' 2>/dev/null || echo "$response"
fi
