#!/usr/bin/env bash
# Complete fix for all Firefly issues
# Usage: ./scripts/fix-firefly-complete.sh

set -euo pipefail

R630_02_IP="192.168.11.12"
ML110_IP="192.168.11.10"
RPC_IP="192.168.11.250"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

echo ""
log_info "═══════════════════════════════════════════════════════════"
log_info "  COMPLETE FIREFLY FIX"
log_info "═══════════════════════════════════════════════════════════"
echo ""

# Fix VMID 6200 - Ensure port 5001 is removed
log_info "Fixing VMID 6200 - Verifying configuration..."
ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${R630_02_IP} \
    "pct exec 6200 -- bash" <<'EOF'
cd /opt/firefly

# Check if port 5001 still exists
if grep -q '"5001:5001"' docker-compose.yml; then
    echo "Removing port 5001 from firefly-core..."
    # More precise sed command
    sed -i '/firefly-core:/,/^[[:space:]]*[a-z]/ {
        /ports:/,/^[[:space:]]*[a-z]/ {
            /- "5001:5001"/d
        }
    }' docker-compose.yml
    echo "Port 5001 removed"
else
    echo "Port 5001 already removed"
fi

# Verify configuration
echo "Current firefly-core ports:"
grep -A 10 'firefly-core:' docker-compose.yml | grep -E 'ports:|"500' || echo "No ports found"
EOF

# Remove and recreate firefly-core
log_info "Removing and recreating firefly-core container..."
ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${R630_02_IP} \
    "pct exec 6200 -- bash" <<'EOF'
cd /opt/firefly
docker-compose stop firefly-core 2>/dev/null || true
docker rm -f firefly-core 2>/dev/null || true
docker-compose up -d firefly-core
sleep 3
docker ps --format '{{.Names}}\t{{.Status}}' | grep firefly
EOF

# Fix VMID 6201 - Storage and installation
log_info "Fixing VMID 6201 - Storage and installation..."

# Check available storage
AVAILABLE_STORAGE=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${ML110_IP} \
    "pvesm status 2>/dev/null | grep -E 'active|available' | grep -v 'disabled' | head -1 | awk '{print \$1}'" || echo "local")

log_info "Using storage: $AVAILABLE_STORAGE"

# Update storage if needed
CURRENT_STORAGE=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${ML110_IP} \
    "pct config 6201 2>/dev/null | grep '^rootfs:' | sed 's/^rootfs: //' | cut -d':' -f1" || echo "")

if [[ "$CURRENT_STORAGE" == "local-lvm" ]]; then
    log_info "Changing storage from local-lvm to $AVAILABLE_STORAGE..."
    ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${ML110_IP} \
        "pct set 6201 --rootfs ${AVAILABLE_STORAGE}:50 2>&1" || log_warn "Storage change may have failed"
fi

# Start container
log_info "Starting container..."
ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${ML110_IP} \
    "pct start 6201 2>&1" && sleep 3 || log_error "Failed to start container"

# Install Docker if needed
log_info "Installing Docker if needed..."
ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${ML110_IP} \
    "pct exec 6201 -- bash" <<'EOF'
if ! command -v docker >/dev/null 2>&1; then
    apt-get update -qq >/dev/null 2>&1
    apt-get install -y docker.io docker-compose >/dev/null 2>&1
    systemctl enable docker >/dev/null 2>&1
    systemctl start docker >/dev/null 2>&1
    echo "Docker installed"
else
    echo "Docker already installed"
fi
EOF

# Create Firefly installation
log_info "Creating Firefly installation..."
ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${ML110_IP} \
    "pct exec 6201 -- bash" <<EOF
mkdir -p /opt/firefly

cat > /opt/firefly/docker-compose.yml <<'COMPOSE_EOF'
version: '3.8'

services:
  postgres:
    image: postgres:15-alpine
    container_name: firefly-postgres
    environment:
      POSTGRES_USER: firefly
      POSTGRES_PASSWORD: \${DB_PASSWORD:-firefly}
      POSTGRES_DB: firefly
    volumes:
      - postgres-data:/var/lib/postgresql/data
    restart: unless-stopped
    networks:
      - firefly-network

  ipfs:
    image: ipfs/kubo:latest
    container_name: firefly-ipfs
    ports:
      - "5001:5001"
      - "4001:4001"
    volumes:
      - ipfs-data:/data/ipfs
    restart: unless-stopped
    networks:
      - firefly-network

  firefly-core:
    image: ghcr.io/hyperledger/firefly:latest
    container_name: firefly-core
    depends_on:
      - postgres
      - ipfs
    environment:
      - FF_DATABASE_TYPE=postgres
      - FF_DATABASE_URL=postgres://firefly:\${DB_PASSWORD:-firefly}@postgres:5432/firefly?sslmode=disable
      - FF_BLOCKCHAIN_TYPE=ethereum
      - FF_BLOCKCHAIN_RPC=http://${RPC_IP}:8545
      - FF_BLOCKCHAIN_WS=ws://${RPC_IP}:8546
      - FF_CHAIN_ID=\${CHAIN_ID:-138}
      - FF_NODE_NAME=firefly-node-ali-1
      - FF_API_PUBLICURL=\${PUBLIC_URL:-http://localhost:5000}
      - FF_IPFS_API=http://ipfs:5001
      - FF_IPFS_GATEWAY=http://ipfs:8080
      - FF_LOGGING_LEVEL=info
    ports:
      - "5000:5000"
    volumes:
      - firefly-data:/var/lib/firefly
    restart: unless-stopped
    networks:
      - firefly-network

volumes:
  postgres-data:
  ipfs-data:
  firefly-data:

networks:
  firefly-network:
    driver: bridge
COMPOSE_EOF

# Create systemd service
cat > /etc/systemd/system/firefly.service <<'SERVICE_EOF'
[Unit]
Description=Hyperledger Firefly
After=docker.service
Requires=docker.service

[Service]
Type=oneshot
RemainAfterExit=yes
WorkingDirectory=/opt/firefly
ExecStart=/usr/bin/docker-compose -f /opt/firefly/docker-compose.yml up -d
ExecStop=/usr/bin/docker-compose -f /opt/firefly/docker-compose.yml down
Restart=on-failure

[Install]
WantedBy=multi-user.target
SERVICE_EOF

systemctl daemon-reload
systemctl enable firefly.service
systemctl start firefly.service
sleep 5
docker ps --format '{{.Names}}\t{{.Status}}' | grep firefly || echo "No containers yet"
EOF

# Final verification
log_info "Final verification..."
echo ""

log_info "VMID 6200 containers:"
ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${R630_02_IP} \
    "pct exec 6200 -- docker ps --format '{{.Names}}\t{{.Status}}' 2>/dev/null | grep firefly" || echo "  No containers"

echo ""
log_info "VMID 6201 containers:"
ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${ML110_IP} \
    "pct exec 6201 -- docker ps --format '{{.Names}}\t{{.Status}}' 2>/dev/null | grep firefly" || echo "  No containers"

echo ""
log_success "═══════════════════════════════════════════════════════════"
log_success "  FIX COMPLETE"
log_success "═══════════════════════════════════════════════════════════"
echo ""
