#!/bin/sh
# DSMS Node Initialization Script
# Creates a private IPFS network for BreakPilot

set -e

echo "=== DSMS Node Initialization ==="

# Generate swarm key for private network if not exists
if [ ! -f "$IPFS_PATH/swarm.key" ]; then
    echo "Generating private network swarm key..."

    # Use predefined swarm key for BreakPilot private network
    # In production, this should be securely generated and shared between nodes
    cat > "$IPFS_PATH/swarm.key" << 'EOF'
/key/swarm/psk/1.0.0/
/base16/
b3c7e8f4a9d2e1c5f8b7a6d4c3e2f1a0b9c8d7e6f5a4b3c2d1e0f9a8b7c6d5e4
EOF

    echo "Swarm key created for private network"
fi

# Configure IPFS for private network
echo "Configuring IPFS for DSMS private network..."

# Remove default bootstrap nodes (we want a private network)
ipfs bootstrap rm --all 2>/dev/null || true

# Configure API to listen on all interfaces (for Docker)
ipfs config Addresses.API /ip4/0.0.0.0/tcp/5001

# Configure Gateway
ipfs config Addresses.Gateway /ip4/0.0.0.0/tcp/8080

# Enable CORS for BreakPilot
ipfs config --json API.HTTPHeaders.Access-Control-Allow-Origin '["http://localhost:8000", "http://backend:8000", "*"]'
ipfs config --json API.HTTPHeaders.Access-Control-Allow-Methods '["GET", "POST", "PUT", "DELETE"]'
ipfs config --json API.HTTPHeaders.Access-Control-Allow-Headers '["Authorization", "Content-Type", "X-Requested-With"]'

# Configure for server profile (less aggressive DHT)
ipfs config Routing.Type dht
ipfs config --json Swarm.ConnMgr.LowWater 50
ipfs config --json Swarm.ConnMgr.HighWater 200
ipfs config --json Swarm.ConnMgr.GracePeriod '"60s"'

# Enable garbage collection
ipfs config --json Datastore.GCPeriod '"1h"'
ipfs config --json Datastore.StorageMax '"10GB"'

# Configure for BreakPilot metadata tagging
ipfs config --json Experimental.FilestoreEnabled true

echo "=== DSMS Node Configuration Complete ==="
echo "Private Network Key: $(cat $IPFS_PATH/swarm.key | tail -1 | head -c 16)..."
echo "API: http://0.0.0.0:5001"
echo "Gateway: http://0.0.0.0:8080"
