#!/usr/bin/env bash
# Fix Firefly Docker image issue (VMID 6200)
# The image hyperledger/firefly:v1.2.0 doesn't exist - need to use correct image
# Usage: ./scripts/fix-firefly-image.sh

set -euo pipefail

NODE_IP="192.168.11.12"
VMID=6200

# 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"; }

log_info "Fixing Firefly Docker image issue..."

# Check current docker-compose.yml
log_info "Checking current docker-compose.yml..."
COMPOSE_FILE="/opt/firefly/docker-compose.yml"

CURRENT_IMAGE=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${NODE_IP} \
    "pct exec $VMID -- grep -i 'image:' $COMPOSE_FILE 2>/dev/null | head -1 | awk '{print \$2}'" || echo "")

log_info "Current image: $CURRENT_IMAGE"

# The correct Firefly image is likely hyperledger/firefly-core or ghcr.io/hyperledger/firefly
# Let's check what's available and update
log_info "Updating to correct Firefly image..."

# Try to find the correct image name
# Common Firefly images:
# - ghcr.io/hyperledger/firefly:latest
# - hyperledger/firefly-core:latest
# - ghcr.io/hyperledger/firefly-core:latest

CORRECT_IMAGE="ghcr.io/hyperledger/firefly:latest"

log_info "Updating docker-compose.yml to use: $CORRECT_IMAGE"

# Update docker-compose.yml
ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${NODE_IP} \
    "pct exec $VMID -- bash" <<EOF
if [[ -f $COMPOSE_FILE ]]; then
    # Backup original
    cp $COMPOSE_FILE ${COMPOSE_FILE}.backup.\$(date +%Y%m%d_%H%M%S)
    
    # Update image (replace hyperledger/firefly with correct image)
    sed -i "s|image:.*hyperledger/firefly.*|image: $CORRECT_IMAGE|g" $COMPOSE_FILE
    sed -i "s|image:.*hyperledger/firefly-core.*|image: $CORRECT_IMAGE|g" $COMPOSE_FILE
    
    echo "Updated docker-compose.yml"
else
    echo "ERROR: docker-compose.yml not found"
    exit 1
fi
EOF

if [[ $? -eq 0 ]]; then
    log_success "Updated docker-compose.yml"
    
    # Reset failed state
    log_info "Resetting service failed state..."
    ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${NODE_IP} \
        "pct exec $VMID -- systemctl reset-failed firefly.service 2>/dev/null || true"
    
    # Try to start service
    log_info "Starting Firefly service..."
    if ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${NODE_IP} \
        "pct exec $VMID -- systemctl start firefly.service 2>&1"; then
        sleep 5
        
        STATUS=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${NODE_IP} \
            "pct exec $VMID -- systemctl is-active firefly.service 2>/dev/null || echo 'inactive'")
        
        if [[ "$STATUS" == "active" ]]; then
            log_success "✅ Firefly service is now active"
        else
            log_warn "Service status unclear. Checking logs..."
            ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${NODE_IP} \
                "pct exec $VMID -- journalctl -u firefly.service -n 10 --no-pager 2>/dev/null | tail -5" || true
        fi
    else
        log_error "Failed to start service"
        log_info "The image may need to be pulled manually or the image name may be different"
        log_info "You may need to check the Firefly documentation for the correct image name"
    fi
else
    log_error "Failed to update docker-compose.yml"
fi
