#!/bin/bash
# Veza V5 Ultra Deployment Script
# Deploys Veza using Ansible + Incus/OVN + HAProxy-in-container + Let's Encrypt

set -euo pipefail

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

# Configuration
INVENTORY="ansible/inventory/prod/hosts.yml"
DOMAIN="veza.talas.fr"
ACME_EMAIL="ops@talas.fr"
TARGET_HOST="192.168.0.12"

# Functions
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

check_prerequisites() {
    log_info "Checking prerequisites..."
    
    # Check if ansible is installed
    if ! command -v ansible-playbook &> /dev/null; then
        log_error "ansible-playbook is not installed. Please install Ansible first."
        exit 1
    fi
    
    # Check if inventory file exists
    if [[ ! -f "$INVENTORY" ]]; then
        log_error "Inventory file $INVENTORY not found!"
        exit 1
    fi
    
    # Check if playbooks exist
    for playbook in ansible/playbooks/00-bootstrap-remote.yml ansible/playbooks/10-incus-ovn.yml ansible/playbooks/20-incus-containers.yml ansible/playbooks/30-haproxy-in-container.yml ansible/playbooks/40-veza-apps.yml ansible/playbooks/50-smoke.yml; do
        if [[ ! -f "$playbook" ]]; then
            log_error "Playbook $playbook not found!"
            exit 1
        fi
    done
    
    # Check SSH connectivity
    log_info "Testing SSH connectivity to $TARGET_HOST..."
    if ! ssh -o ConnectTimeout=10 -o BatchMode=yes senke@$TARGET_HOST "echo 'SSH connection successful'" &> /dev/null; then
        log_error "Cannot connect to $TARGET_HOST via SSH. Please check your SSH key and connectivity."
        exit 1
    fi
    
    log_success "Prerequisites check passed!"
}

run_playbook() {
    local playbook="$1"
    local description="$2"
    local extra_vars="$3"
    
    log_info "Running: $description"
    log_info "Playbook: $playbook"
    
    if [[ -n "$extra_vars" ]]; then
        log_info "Extra vars: $extra_vars"
        ansible-playbook -i "$INVENTORY" "$playbook" -e "$extra_vars" -v
    else
        ansible-playbook -i "$INVENTORY" "$playbook" -v
    fi
    
    if [[ $? -eq 0 ]]; then
        log_success "$description completed successfully!"
    else
        log_error "$description failed!"
        exit 1
    fi
}

deploy_veza() {
    log_info "Starting Veza V5 Ultra deployment..."
    log_info "Target host: $TARGET_HOST"
    log_info "Domain: $DOMAIN"
    log_info "ACME Email: $ACME_EMAIL"
    echo
    
    # Step 1: Bootstrap remote host
    run_playbook "ansible/playbooks/00-bootstrap-remote.yml" "Bootstrap Debian host"
    echo
    
    # Step 2: Install Incus + OVN
    run_playbook "ansible/playbooks/10-incus-ovn.yml" "Install Incus + OVN single-host"
    echo
    
    # Step 3: Create containers
    run_playbook "ansible/playbooks/20-incus-containers.yml" "Create Incus containers"
    echo
    
    # Step 4: Configure HAProxy + ACME
    run_playbook "ansible/playbooks/30-haproxy-in-container.yml" "Configure HAProxy + ACME" "domain=$DOMAIN acme_email=$ACME_EMAIL"
    echo
    
    # Step 5: Deploy applications
    run_playbook "ansible/playbooks/40-veza-apps.yml" "Deploy Veza applications"
    echo
    
    # Step 6: Run smoke tests
    run_playbook "ansible/playbooks/50-smoke.yml" "Run smoke tests"
    echo
    
    log_success "Veza V5 Ultra deployment completed successfully!"
    echo
    log_info "Next steps:"
    log_info "1. Point DNS A record for $DOMAIN to $TARGET_HOST"
    log_info "2. Re-run HAProxy playbook to get Let's Encrypt certificate:"
    log_info "   ansible-playbook -i $INVENTORY ansible/playbooks/30-haproxy-in-container.yml -e domain=$DOMAIN -e acme_email=$ACME_EMAIL"
    log_info "3. Test full functionality with real domain"
    echo
    log_info "Access URLs:"
    log_info "- HTTP:  http://$TARGET_HOST/"
    log_info "- HTTPS: https://$TARGET_HOST/ (self-signed cert until DNS is configured)"
    log_info "- API:   https://$TARGET_HOST/api/"
    log_info "- WS:    wss://$TARGET_HOST/ws/"
    log_info "- Stream: https://$TARGET_HOST/stream/"
}

show_help() {
    echo "Veza V5 Ultra Deployment Script"
    echo
    echo "Usage: $0 [OPTIONS]"
    echo
    echo "Options:"
    echo "  -h, --help              Show this help message"
    echo "  -d, --domain DOMAIN     Set domain (default: $DOMAIN)"
    echo "  -e, --email EMAIL       Set ACME email (default: $ACME_EMAIL)"
    echo "  -t, --target HOST       Set target host (default: $TARGET_HOST)"
    echo "  --bootstrap-only        Run only bootstrap playbook"
    echo "  --infra-only            Run bootstrap + infrastructure playbooks"
    echo "  --apps-only             Run only applications playbook"
    echo "  --test-only             Run only smoke tests"
    echo
    echo "Examples:"
    echo "  $0                                    # Full deployment"
    echo "  $0 -d myapp.example.com -e admin@example.com  # Custom domain and email"
    echo "  $0 --bootstrap-only                   # Only bootstrap the host"
    echo "  $0 --infra-only                       # Only setup infrastructure"
}

# Parse command line arguments
BOOTSTRAP_ONLY=false
INFRA_ONLY=false
APPS_ONLY=false
TEST_ONLY=false

while [[ $# -gt 0 ]]; do
    case $1 in
        -h|--help)
            show_help
            exit 0
            ;;
        -d|--domain)
            DOMAIN="$2"
            shift 2
            ;;
        -e|--email)
            ACME_EMAIL="$2"
            shift 2
            ;;
        -t|--target)
            TARGET_HOST="$2"
            shift 2
            ;;
        --bootstrap-only)
            BOOTSTRAP_ONLY=true
            shift
            ;;
        --infra-only)
            INFRA_ONLY=true
            shift
            ;;
        --apps-only)
            APPS_ONLY=true
            shift
            ;;
        --test-only)
            TEST_ONLY=true
            shift
            ;;
        *)
            log_error "Unknown option: $1"
            show_help
            exit 1
            ;;
    esac
done

# Main execution
main() {
    log_info "Veza V5 Ultra Deployment Script"
    log_info "================================"
    echo
    
    check_prerequisites
    
    if [[ "$BOOTSTRAP_ONLY" == true ]]; then
        run_playbook "ansible/playbooks/00-bootstrap-remote.yml" "Bootstrap Debian host"
    elif [[ "$INFRA_ONLY" == true ]]; then
        run_playbook "ansible/playbooks/00-bootstrap-remote.yml" "Bootstrap Debian host"
        run_playbook "ansible/playbooks/10-incus-ovn.yml" "Install Incus + OVN single-host"
        run_playbook "ansible/playbooks/20-incus-containers.yml" "Create Incus containers"
        run_playbook "ansible/playbooks/30-haproxy-in-container.yml" "Configure HAProxy + ACME" "domain=$DOMAIN acme_email=$ACME_EMAIL"
    elif [[ "$APPS_ONLY" == true ]]; then
        run_playbook "ansible/playbooks/40-veza-apps.yml" "Deploy Veza applications"
    elif [[ "$TEST_ONLY" == true ]]; then
        run_playbook "ansible/playbooks/50-smoke.yml" "Run smoke tests"
    else
        deploy_veza
    fi
}

# Run main function
main "$@"
