#!/bin/bash
set -e

# IPFS distribution script for Rune* Ecosystem
# Uploads releases to IPFS and updates IPNS

IPFS_API="${IPFS_API:-https://api.pinata.cloud}"
IPNS_KEY="${IPNS_KEY:-rune-ecosystem-forge}"

echo "📌 Uploading to IPFS..."

# Create distribution directory
mkdir -p ipfs-dist/{binaries,schemas,docs}

# Copy release artifacts
cp -r target/release/runeforge* ipfs-dist/binaries/ 2>/dev/null || true
cp -r schemas/* ipfs-dist/schemas/
cp -r docs/* ipfs-dist/docs/

# Create manifest
cat > ipfs-dist/manifest.json << EOF
{
  "name": "runeforge",
  "version": "25.08.0",
  "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
  "binaries": {
    "linux-x64": "/binaries/runeforge-linux-x64",
    "darwin-arm64": "/binaries/runeforge-darwin-arm64",
    "windows-x64": "/binaries/runeforge-windows-x64.exe"
  },
  "schemas": {
    "blueprint": "/schemas/blueprint.schema.json",
    "stack": "/schemas/stack.schema.json"
  }
}
EOF

# Upload to IPFS (using local node or pinning service)
if command -v ipfs &> /dev/null; then
    HASH=$(ipfs add -r ipfs-dist --quiet | tail -1)
    echo "✅ Uploaded to IPFS: $HASH"
    
    # Update IPNS if key exists
    if ipfs key list | grep -q "$IPNS_KEY"; then
        ipfs name publish --key="$IPNS_KEY" "/ipfs/$HASH"
        echo "✅ IPNS updated: /ipns/$(ipfs key list -l | grep $IPNS_KEY | awk '{print $1}')"
    fi
else
    echo "⚠️  IPFS not installed, would upload to pinning service"
fi

# Mirror to Web3.Storage / Pinata as backup
# curl -X POST https://api.web3.storage/upload ...