#!/bin/bash

# BZZZ Cluster Deployment Script
set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
VERSION="1.0.2"

echo "🚀 BZZZ Cluster Deployment v${VERSION}"
echo "========================================"

# Check if binary exists
BINARY_PATH="${SCRIPT_DIR}/build/bzzz-${VERSION}"
if [[ ! -f "$BINARY_PATH" ]]; then
    echo "❌ Binary not found: $BINARY_PATH"
    echo "   Please build the binary first with: go build -o build/bzzz-${VERSION} ."
    exit 1
fi

echo "✅ Binary found: $BINARY_PATH ($(ls -lh "$BINARY_PATH" | awk '{print $5}'))"

# Check if inventory exists
INVENTORY_PATH="${SCRIPT_DIR}/inventory.ini"
if [[ ! -f "$INVENTORY_PATH" ]]; then
    echo "❌ Inventory file not found: $INVENTORY_PATH"
    exit 1
fi

echo "✅ Inventory file found: $INVENTORY_PATH"

# Check for local config file (as a reference)
LOCAL_CONFIG_PATHS=(
    "${SCRIPT_DIR}/bzzz.yaml"
    "${SCRIPT_DIR}/config/bzzz.yaml"
    "$HOME/.config/bzzz/config.yaml"
    "/etc/bzzz/config.yaml"
)

echo ""
echo "🔍 Local config file check (reference):"
LOCAL_CONFIG_FOUND=false
for config_path in "${LOCAL_CONFIG_PATHS[@]}"; do
    if [[ -f "$config_path" ]]; then
        echo "   ✅ Found: $config_path"
        LOCAL_CONFIG_FOUND=true
    else
        echo "   ❌ Missing: $config_path"
    fi
done

if [[ "$LOCAL_CONFIG_FOUND" == "false" ]]; then
    echo ""
    echo "⚠️  WARNING: No BZZZ config files found locally!"
    echo "   The embedded installation server should have generated config files."
    echo "   Remote machines will also be checked during deployment."
fi

# Read password from secrets file
PASSWORD_FILE="/home/tony/chorus/business/secrets/tony-pass"
if [[ ! -f "$PASSWORD_FILE" ]]; then
    echo "❌ Password file not found: $PASSWORD_FILE"
    echo "   Please enter password manually when prompted"
    EXTRA_VARS=""
else
    PASSWORD=$(cat "$PASSWORD_FILE")
    EXTRA_VARS="--extra-vars ansible_ssh_pass='$PASSWORD'"
    echo "✅ Password loaded from secrets file"
fi

echo ""
echo "📋 Deployment Plan:"
echo "   • Verify BZZZ configuration files exist"
echo "   • Stop existing BZZZ services"
echo "   • Backup current binaries" 
echo "   • Deploy BZZZ v${VERSION}"
echo "   • Update systemd configuration"
echo "   • Start services and verify connectivity"
echo ""

# Confirm deployment
read -p "🔄 Proceed with cluster deployment? (y/N): " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "❌ Deployment cancelled"
    exit 0
fi

echo "🚀 Starting deployment..."

# Run Ansible playbook
eval "ansible-playbook -i '$INVENTORY_PATH' '$SCRIPT_DIR/deploy-bzzz-cluster.yml' $EXTRA_VARS --become"

echo ""
echo "✅ Deployment complete!"
echo ""
echo "🔍 To verify deployment:"
echo "   ansible bzzz_cluster -i inventory.ini -m shell -a 'systemctl status bzzz' --become $EXTRA_VARS"
echo ""
echo "📝 To view logs:"
echo "   ansible bzzz_cluster -i inventory.ini -m shell -a 'journalctl -u bzzz --since \"5 minutes ago\" --no-pager' --become $EXTRA_VARS"