#!/bin/bash
set -e
echo "=============================================="
echo "   BricsCoin Node - Automatic Setup v3.0"
echo "=============================================="

echo "[1/7] Checking Docker..."
if ! command -v docker &> /dev/null; then
    echo "Error: Docker not installed! Download from: https://docker.com"
    exit 1
fi

echo "[2/7] Checking Docker Compose..."
if ! docker compose version &> /dev/null; then
    echo "Error: Docker Compose not found!"
    exit 1
fi

echo "[3/7] Creating directory..."
mkdir -p ~/bricscoin-node && cd ~/bricscoin-node

echo "[4/7] Downloading BricsCoin..."
if [ -d "Bricscoin" ]; then cd Bricscoin && git pull && cd ..; else git clone https://codeberg.org/Bricscoin_26/Bricscoin.git; fi
cd Bricscoin

echo "[5/7] Downloading blockchain..."
curl -L -o bricscoin-backup.gz https://bricscoin26.org/downloads/bricscoin-backup.gz

echo "[6/7] Starting node..."
docker compose -f docker-compose.node.yml up -d
sleep 10
docker cp bricscoin-backup.gz bricscoin-db:/tmp/
docker exec bricscoin-db mongorestore --db bricscoin --archive=/tmp/bricscoin-backup.gz --gzip --drop
rm -f bricscoin-backup.gz

echo "[7/7] Registering node..."
NODE_ID="node-$(hostname)-$(date +%s | tail -c 5)"
PUBLIC_IP=$(curl -s ifconfig.me)
curl -s -X POST https://bricscoin26.org/api/p2p/register -H "Content-Type: application/json" -d "{"node_id": "$NODE_ID", "url": "http://$PUBLIC_IP:8001"}" > /dev/null

echo ""
echo "====== BricsCoin Node Ready! ======"
echo "Node ID: $NODE_ID"
echo "IP: $PUBLIC_IP"
