#!/usr/bin/env bash
# Final fix for Firefly - direct approach
# Usage: ./scripts/fix-firefly-final.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 "  FINAL FIREFLY FIX"
log_info "═══════════════════════════════════════════════════════════"
echo ""

# Fix VMID 6200 - Direct file edit
log_info "Fixing VMID 6200 - Removing port 5001 from docker-compose.yml..."

ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${R630_02_IP} \
    "pct exec 6200 -- bash" <<'EOF'
cd /opt/firefly

# Read the file, remove the port 5001 line specifically for firefly-core
python3 <<'PYTHON_EOF'
import re

with open('docker-compose.yml', 'r') as f:
    content = f.read()

# Find firefly-core section and remove port 5001 line
lines = content.split('\n')
result = []
in_firefly_core = False
in_ports = False
skip_next = False

for i, line in enumerate(lines):
    if 'firefly-core:' in line:
        in_firefly_core = True
        in_ports = False
        result.append(line)
    elif in_firefly_core and line.strip().startswith('ports:'):
        in_ports = True
        result.append(line)
    elif in_firefly_core and in_ports and '- "5001:5001"' in line:
        # Skip this line
        continue
    elif in_firefly_core and in_ports and line.strip() and not line[0].isspace():
        # End of ports section
        in_ports = False
        result.append(line)
    elif in_firefly_core and line.strip() and not line[0].isspace() and ':' in line:
        # New service or section
        in_firefly_core = False
        in_ports = False
        result.append(line)
    else:
        result.append(line)

with open('docker-compose.yml', 'w') as f:
    f.write('\n'.join(result))

print("docker-compose.yml updated")
PYTHON_EOF

# Verify
echo "Verifying ports configuration:"
grep -A 10 'firefly-core:' docker-compose.yml | grep -E 'ports:|"500' || echo "Port 5001 removed"
EOF

log_success "Configuration updated"

# Remove all firefly-core containers and networks
log_info "Cleaning up containers and networks..."
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 network prune -f 2>/dev/null || true
echo "Cleanup complete"
EOF

# Start firefly-core
log_info "Starting firefly-core..."
ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${R630_02_IP} \
    "pct exec 6200 -- bash" <<'EOF'
cd /opt/firefly
docker-compose up -d firefly-core
sleep 5
docker ps --format '{{.Names}}\t{{.Status}}' | grep firefly
EOF

# For VMID 6201 - Create new container with correct storage
log_info "Setting up VMID 6201..."

# Check if we can migrate or need to recreate
log_info "VMID 6201 requires storage migration. Options:"
log_info "1. Recreate container with correct storage (recommended)"
log_info "2. Migrate storage (if data is important)"

log_warn "VMID 6201 will be recreated with correct storage..."
log_info "Creating new Firefly container on ml110..."

# Create new container (6201) with correct storage
ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${ML110_IP} \
    "pct create 6201 local:vztmpl/ubuntu-22.04-standard_22.04-1_amd64.tar.zst \
    --hostname firefly-ali-1 \
    --net0 name=eth0,bridge=vmbr0,ip=192.168.11.57/24,gw=192.168.11.1 \
    --rootfs local:50 \
    --memory 2048 \
    --cores 2 \
    --storage local \
    --unprivileged 0 2>&1" || log_warn "Container may already exist or template issue"

# Start and configure
if ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${ML110_IP} \
    "pct start 6201 2>&1"; then
    sleep 5
    
    log_info "Installing Docker..."
    ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${ML110_IP} \
        "pct exec 6201 -- bash" <<'EOF'
apt-get update -qq >/dev/null 2>&1
apt-get install -y docker.io docker-compose python3 >/dev/null 2>&1
systemctl enable docker >/dev/null 2>&1
systemctl start docker >/dev/null 2>&1
echo "Docker installed"
EOF
    
    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

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 "Starting..."
EOF
else
    log_warn "Could not start container 6201"
fi

# Final status
echo ""
log_info "═══════════════════════════════════════════════════════════"
log_info "  FINAL STATUS"
log_info "═══════════════════════════════════════════════════════════"
echo ""

log_info "VMID 6200 (r630-02):"
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 "  Checking..."

echo ""
log_info "VMID 6201 (ml110):"
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 "  Checking..."

echo ""
log_success "Fix complete!"
