#!/bin/bash
set -e

# Secure Deployment Script - Uses SSH keys instead of passwords
# 
# SETUP INSTRUCTIONS:
# 1. Generate SSH key pair if you don't have one: ssh-keygen -t ed25519 -C "your_email@example.com"
# 2. Copy public key to servers: ssh-copy-id user@server
# 3. Test connection: ssh user@server
# 4. Update .env file with server details (no passwords needed)

# Get script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

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

# Load environment variables
if [ -f .env ]; then
    export $(cat .env | sed 's/#.*//g' | xargs)
fi

# Function to display usage
usage() {
    echo "Usage: $0 [staging|production|prod]"
    echo "  staging    - Deploy to staging server (default)"
    echo "  production - Deploy to production server (requires confirmation)"
    echo "  prod       - Alias for production"
    echo ""
    echo "Prerequisites:"
    echo "  - SSH key authentication must be configured"
    echo "  - No passwords are used in this script for security"
    exit 1
}

# Function to check SSH key authentication
check_ssh_auth() {
    local server=$1
    local user=$2
    
    echo -e "${YELLOW}Checking SSH key authentication...${NC}"
    
    if ssh -o BatchMode=yes -o ConnectTimeout=5 "$user@$server" echo "SSH key auth successful" 2>/dev/null; then
        echo -e "${GREEN}✓ SSH key authentication verified${NC}"
        return 0
    else
        echo -e "${RED}✗ SSH key authentication failed${NC}"
        echo -e "${RED}Please set up SSH keys before using this script:${NC}"
        echo "  1. Generate key: ssh-keygen -t ed25519"
        echo "  2. Copy to server: ssh-copy-id $user@$server"
        echo "  3. Test: ssh $user@$server"
        return 1
    fi
}

# Determine environment
ENVIRONMENT="${1:-staging}"
if [ "$ENVIRONMENT" = "prod" ]; then
    ENVIRONMENT="production"
fi

# Validate environment
if [ "$ENVIRONMENT" != "staging" ] && [ "$ENVIRONMENT" != "production" ]; then
    echo -e "${RED}Error: Invalid environment '$ENVIRONMENT'${NC}"
    usage
fi

# Set variables based on environment
if [ "$ENVIRONMENT" = "staging" ]; then
    SERVER_IP=$UPSKILL_STAGING_IP
    SSH_USER=$UPSKILL_STAGING_SSH_USER
    SERVER_PATH=$UPSKILL_STAGING_PATH
    SITE_URL=$UPSKILL_STAGING_URL
    ENV_NAME="STAGING"
    ENV_COLOR=$YELLOW
else
    SERVER_IP=$UPSKILL_PROD_IP
    SSH_USER=$UPSKILL_PROD_SSH_USER
    SERVER_PATH=$UPSKILL_PROD_PATH
    SITE_URL=$UPSKILL_PROD_URL
    ENV_NAME="PRODUCTION"
    ENV_COLOR=$RED
fi

# Production safety check
if [ "$ENVIRONMENT" = "production" ]; then
    echo -e "${RED}⚠️  WARNING: You are about to deploy to PRODUCTION!${NC}"
    echo -e "${RED}This will affect the live site at $SITE_URL${NC}"
    echo ""
    read -p "Type 'DEPLOY TO PRODUCTION' to confirm: " confirm
    
    if [ "$confirm" != "DEPLOY TO PRODUCTION" ]; then
        echo -e "${YELLOW}Deployment cancelled.${NC}"
        exit 0
    fi
    
    # Double confirmation for production
    echo ""
    echo -e "${RED}⚠️  FINAL CONFIRMATION REQUIRED${NC}"
    read -p "Are you absolutely sure? (yes/no): " final_confirm
    
    if [ "$final_confirm" != "yes" ]; then
        echo -e "${YELLOW}Deployment cancelled.${NC}"
        exit 0
    fi
fi

# Validate required variables
if [ -z "$SERVER_IP" ] || [ -z "$SSH_USER" ] || [ -z "$SERVER_PATH" ]; then
    echo -e "${RED}Error: Missing required environment variables for $ENVIRONMENT${NC}"
    echo "Please check your .env file"
    exit 1
fi

# Check SSH authentication
if ! check_ssh_auth "$SERVER_IP" "$SSH_USER"; then
    exit 1
fi

# Display deployment info
echo -e "${ENV_COLOR}=== HVAC Community Events Secure Deployment ===${NC}"
echo "Date: $(date)"
echo ""
echo -e "${YELLOW}Target Environment:${NC} ${ENV_COLOR}$ENV_NAME${NC}"
echo -e "${YELLOW}Target Server:${NC} $SERVER_IP"
echo -e "${YELLOW}Target Path:${NC} $SERVER_PATH/wp-content/plugins/hvac-community-events"
echo -e "${YELLOW}Site URL:${NC} $SITE_URL"
echo -e "${GREEN}Authentication:${NC} SSH Key (Secure)"
echo ""

# Pre-deployment validation
if [ ! -f ".skip-validation" ]; then
    echo -e "${YELLOW}Running pre-deployment validation...${NC}"
    if [ -f "$SCRIPT_DIR/pre-deployment-check.sh" ]; then
        "$SCRIPT_DIR/pre-deployment-check.sh"
        if [ $? -ne 0 ]; then
            echo -e "${RED}Pre-deployment validation failed!${NC}"
            echo "To skip validation for emergency deployment, create a .skip-validation file"
            exit 1
        fi
    else
        echo -e "${YELLOW}Pre-deployment check script not found, skipping validation${NC}"
    fi
else
    echo -e "${YELLOW}⚠️  Skipping pre-deployment validation for emergency fix deployment${NC}"
fi

# Create deployment package
echo -e "${GREEN}Creating deployment package...${NC}"
TEMP_DIR=$(mktemp -d)
PLUGIN_DIR="$TEMP_DIR/hvac-community-events"

# Copy plugin files
mkdir -p "$PLUGIN_DIR"
cp -r includes "$PLUGIN_DIR/"
cp -r templates "$PLUGIN_DIR/"
cp -r assets "$PLUGIN_DIR/"
cp hvac-community-events.php "$PLUGIN_DIR/"
cp README.md "$PLUGIN_DIR/" 2>/dev/null || true

# Create deployment zip
cd "$TEMP_DIR"
zip -r hvac-community-events.zip hvac-community-events > /dev/null

# Deploy to server
echo ""
echo -e "${GREEN}Step 1: Creating backup on server...${NC}"
ssh "$SSH_USER@$SERVER_IP" "cd $SERVER_PATH/wp-content/plugins && \
    if [ -d hvac-community-events ]; then \
        mkdir -p hvac-backups && \
        cp -r hvac-community-events hvac-backups/hvac-community-events-backup-\$(date +%Y%m%d-%H%M%S); \
    fi"

echo -e "${GREEN}Step 2: Uploading deployment package...${NC}"
ssh "$SSH_USER@$SERVER_IP" "mkdir -p ~/tmp"
scp "$TEMP_DIR/hvac-community-events.zip" "$SSH_USER@$SERVER_IP:~/tmp/"

echo -e "${GREEN}Step 3: Extracting and deploying...${NC}"
ssh "$SSH_USER@$SERVER_IP" "cd $SERVER_PATH && \
    mv ~/tmp/hvac-community-events.zip wp-content/plugins/ && \
    cd wp-content/plugins && \
    rm -rf hvac-community-events && \
    unzip -q hvac-community-events.zip && \
    chmod -R 755 hvac-community-events && \
    rm hvac-community-events.zip && \
    echo 'Deployment complete!'"

echo -e "${GREEN}Step 4: Clearing cache...${NC}"
ssh "$SSH_USER@$SERVER_IP" "cd $SERVER_PATH && \
    wp cache flush 2>/dev/null || echo 'WP-CLI cache flush not available' && \
    wp breeze purge --cache=all 2>/dev/null || echo 'Breeze cache plugin not available' && \
    wp eval 'if (function_exists(\"opcache_reset\")) { opcache_reset(); echo \"OPcache cleared\"; }' 2>/dev/null || echo 'OPcache reset not available'"

echo -e "${GREEN}Step 5: Activating plugin and creating pages...${NC}"
ssh "$SSH_USER@$SERVER_IP" "cd $SERVER_PATH && \
    echo 'Deactivating plugin to ensure clean activation...' && \
    wp plugin deactivate hvac-community-events --quiet && \
    echo 'Activating plugin (this triggers page creation)...' && \
    wp plugin activate hvac-community-events --quiet && \
    echo 'Updating page templates...' && \
    PAGE_ID=\$(wp post list --post_type=page --name=dashboard --field=ID | head -1) && \
    if [ ! -z \"\$PAGE_ID\" ]; then \
        wp post meta update \$PAGE_ID _wp_page_template templates/page-trainer-dashboard.php --quiet && \
        echo '✅ Dashboard template updated'; \
    fi && \
    echo 'Flushing rewrite rules...' && \
    wp rewrite flush --quiet && \
    if wp plugin list --name=hvac-community-events --status=active --format=count | grep -q '1'; then \
        echo '✅ Plugin activated successfully'; \
    else \
        echo '❌ Plugin activation failed!'; \
    fi"

echo -e "${GREEN}Step 6: Verifying deployment...${NC}"
ssh "$SSH_USER@$SERVER_IP" "cd $SERVER_PATH && \
    echo 'Checking if key pages exist...' && \
    if wp post list --post_type=page --name=training-login --format=count | grep -q '1'; then \
        echo '✅ Login page exists'; \
    else \
        echo '❌ Login page missing'; \
    fi && \
    if wp post list --post_type=page --name=certificate-reports --format=count | grep -q '1'; then \
        echo '✅ Certificate reports page exists'; \
    else \
        echo '❌ Certificate reports page missing'; \
    fi"

# Security audit after deployment
echo -e "${GREEN}Step 7: Running security checks...${NC}"
ssh "$SSH_USER@$SERVER_IP" "cd $SERVER_PATH && \
    echo 'Checking file permissions...' && \
    find wp-content/plugins/hvac-community-events -type f -exec chmod 644 {} \; && \
    find wp-content/plugins/hvac-community-events -type d -exec chmod 755 {} \; && \
    echo '✅ File permissions secured'"

# Cleanup
rm -rf "$TEMP_DIR"

echo ""
echo -e "${GREEN}=== Deployment Complete! ===${NC}"
echo ""
echo -e "${YELLOW}✅ Plugin deployed to ${ENV_COLOR}$ENV_NAME${NC}"
echo ""
echo -e "${YELLOW}Test URLs:${NC}"
echo "1. Login: ${SITE_URL}training-login/"
echo "2. Certificate Reports: ${SITE_URL}trainer/certificate-reports/"
echo "3. Dashboard: ${SITE_URL}trainer/dashboard/"
echo "4. Master Dashboard: ${SITE_URL}master-trainer/dashboard/"
echo ""

if [ "$ENVIRONMENT" = "production" ]; then
    echo -e "${RED}⚠️  IMPORTANT: This was a PRODUCTION deployment!${NC}"
    echo -e "${RED}Please verify the site is working correctly at $SITE_URL${NC}"
    echo -e "${RED}Monitor error logs for any issues.${NC}"
fi

echo ""
echo -e "${YELLOW}Rollback Instructions (if needed):${NC}"
echo "ssh $SSH_USER@$SERVER_IP"
echo "cd $SERVER_PATH"
echo "rm -rf wp-content/plugins/hvac-community-events"
echo "cp -r wp-content/plugins/hvac-backups/hvac-community-events-backup-[date] wp-content/plugins/hvac-community-events"
echo "wp plugin activate hvac-community-events"
echo "wp cache flush"