#!/bin/bash

# Quick Production Setup Script for Custom PHP Framework
# Michael Schiemer - michaelschiemer.de
# Usage: ./quick-setup.sh [environment]

set -euo pipefail

# Configuration
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
INFRASTRUCTURE_DIR="${SCRIPT_DIR}/infrastructure"
APPLICATIONS_DIR="${SCRIPT_DIR}/applications"
DEFAULT_ENV="production"

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

log() {
    echo -e "${GREEN}[$(date +'%H:%M:%S')] ✅ $1${NC}"
}

warn() {
    echo -e "${YELLOW}[$(date +'%H:%M:%S')] ⚠️  $1${NC}"
}

error() {
    echo -e "${RED}[$(date +'%H:%M:%S')] ❌ $1${NC}"
}

info() {
    echo -e "${BLUE}[$(date +'%H:%M:%S')] ℹ️  $1${NC}"
}

# Get environment
DEPLOY_ENV="${1:-$DEFAULT_ENV}"

if [[ "$DEPLOY_ENV" != "production" && "$DEPLOY_ENV" != "staging" ]]; then
    error "Invalid environment: $DEPLOY_ENV"
    echo "Usage: $0 [production|staging]"
    exit 1
fi

echo -e "${BLUE}================================${NC}"
echo -e "${BLUE}Custom PHP Framework Quick Setup${NC}"
echo -e "${BLUE}Environment: ${DEPLOY_ENV^}${NC}"
echo -e "${BLUE}Domain: michaelschiemer.de${NC}"
echo -e "${BLUE}================================${NC}"
echo

# Step 1: Check prerequisites
log "Checking prerequisites..."

# Check if SSH key exists
SSH_KEY="/home/michael/.ssh/production"
if [[ ! -f "$SSH_KEY" ]]; then
    error "SSH key not found: $SSH_KEY"
    info "Generate key with: ssh-keygen -t rsa -b 4096 -f $SSH_KEY"
    exit 1
fi

# Check if Ansible is installed
if ! command -v ansible-playbook &> /dev/null; then
    error "Ansible not installed"
    info "Install with: sudo apt-get update && sudo apt-get install ansible"
    exit 1
fi

log "Prerequisites check complete"

# Step 2: Check server connectivity
log "Testing server connectivity..."

if ssh -i "$SSH_KEY" -o ConnectTimeout=10 -o BatchMode=yes root@94.16.110.151 exit 2>/dev/null; then
    log "Server accessible as root - ready for initial setup"
    FRESH_SETUP=true
elif ssh -i "$SSH_KEY" -o ConnectTimeout=10 -o BatchMode=yes deploy@94.16.110.151 exit 2>/dev/null; then
    log "Server accessible as deploy user - initial setup already done"
    FRESH_SETUP=false
else
    error "Cannot connect to server"
    info "Check SSH key and server status"
    exit 1
fi

# Step 3: Environment configuration
log "Checking environment configuration..."

ENV_FILE="${APPLICATIONS_DIR}/environments/.env.${DEPLOY_ENV}"
if [[ ! -f "$ENV_FILE" ]]; then
    error "Environment file not found: $ENV_FILE"
    info "This has been created from template, please configure:"
    info "nano $ENV_FILE"
    exit 1
fi

# Check for required placeholders
if grep -q "*** REQUIRED" "$ENV_FILE"; then
    warn "Environment file contains placeholders that need configuration:"
    grep "*** REQUIRED" "$ENV_FILE" | head -5
    echo
    echo -e "${YELLOW}Configure these values before proceeding:${NC}"
    echo "nano $ENV_FILE"
    echo
    read -p "Continue anyway? [y/N]: " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        info "Deployment cancelled. Configure environment file first."
        exit 0
    fi
fi

log "Environment configuration check complete"

# Step 4: Execute deployment based on server state
cd "$INFRASTRUCTURE_DIR"

if [ "$FRESH_SETUP" = true ]; then
    log "Executing initial server setup..."
    
    # Run initial setup
    ansible-playbook -i "inventories/${DEPLOY_ENV}/hosts.yml" setup-fresh-server.yml
    
    if [ $? -eq 0 ]; then
        log "Initial setup completed successfully!"
        echo
        warn "IMPORTANT: Update your inventory file:"
        warn "1. Change ansible_user from 'root' to 'deploy'"
        warn "2. Set fresh_server_setup: false"
        echo
        warn "Then run: ./deploy.sh $DEPLOY_ENV"
        exit 0
    else
        error "Initial setup failed!"
        exit 1
    fi
else
    log "Running full deployment..."
    
    # Run full deployment
    cd "$SCRIPT_DIR"
    ./deploy.sh "$DEPLOY_ENV"
    
    if [ $? -eq 0 ]; then
        log "Deployment completed successfully!"
        echo
        echo -e "${GREEN}🎉 Your Custom PHP Framework is now live!${NC}"
        echo -e "${GREEN}🌐 Visit: https://michaelschiemer.de${NC}"
        echo -e "${GREEN}🔍 Health check: https://michaelschiemer.de/health.php${NC}"
        echo
        info "Next steps:"
        info "1. Test all application functionality"
        info "2. Configure monitoring and backups"
        info "3. Set up automated deployments"
    else
        error "Deployment failed!"
        info "Check the error messages above and try again"
        exit 1
    fi
fi