#!/bin/bash

# Load environment variables
ENV_FILE="$(dirname "$0")/../.env"
if [ ! -f "$ENV_FILE" ]; then
    echo "Error: .env file not found at: $ENV_FILE"
    exit 1
fi

source "$ENV_FILE"

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

# Function to check if a command was successful
check_status() {
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✓ $1${NC}"
        return 0
    else
        echo -e "${RED}✗ $1${NC}"
        return 1
    fi
}

# Create backup directory
BACKUP_DIR="backups/$(date +%Y%m%d_%H%M%S)"
mkdir -p "$BACKUP_DIR"
echo -e "${YELLOW}Creating backup in: $BACKUP_DIR${NC}"

# Debug environment variables
echo "Debug: Using SSH user: $UPSKILL_STAGING_SSH_USER"
echo "Debug: Using IP: $UPSKILL_STAGING_IP"
echo "Debug: Using path: $UPSKILL_STAGING_PATH"

# Test SSH connection with password
echo "Testing SSH connection..."
if ! sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "echo 'SSH connection successful'"; then
    echo -e "${RED}Error: Cannot connect to staging server${NC}"
    exit 1
fi
check_status "SSH connection test"

# Download WordPress files (excluding media that exists locally)
echo "Downloading WordPress files (skipping existing media)..."
rsync_cmd="sshpass -p \"$UPSKILL_STAGING_PASS\" rsync -avz --checksum --exclude='wp-config.php' \
    --exclude='.git/' \
    --exclude='node_modules/' \
    --exclude='*.log' \
    --exclude='wp-content/cache/' \
    --existing --ignore-existing \
    \"$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP:$UPSKILL_STAGING_PATH/public_html/\" \"$BACKUP_DIR/wordpress/\""

eval $rsync_cmd
check_status "WordPress files download"

# Export and download database
echo "Exporting staging database..."
sshpass -p "$UPSKILL_STAGING_PASS" ssh "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH/public_html && wp db export - --add-drop-table" > "$BACKUP_DIR/database.sql"
check_status "Database export"

# Download wp-config.php (for reference)
echo "Downloading wp-config.php..."
if sshpass -p "$UPSKILL_STAGING_PASS" scp "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP:$UPSKILL_STAGING_PATH/public_html/wp-config.php" "$BACKUP_DIR/wp-config.php.staging"; then
    echo -e "${GREEN}✓ wp-config.php download${NC}"
else
    echo -e "${YELLOW}⚠ wp-config.php not found at standard location${NC}"
    echo "Debug: Found wp-config.php at: /home/974670.cloudwaysapps.com/uberrxmprk/public_html/wp-config.php"
    if sshpass -p "$UPSKILL_STAGING_PASS" scp "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP:/home/974670.cloudwaysapps.com/uberrxmprk/public_html/wp-config.php" "$BACKUP_DIR/wp-config.php.staging"; then
        echo -e "${GREEN}✓ wp-config.php downloaded from alternate path${NC}"
    else
        echo -e "${YELLOW}⚠ Could not download wp-config.php${NC}"
    fi
fi

# Create manifest file
echo "Creating backup manifest..."
cat > "$BACKUP_DIR/manifest.txt" <<EOF
Staging Backup Manifest
========================
Date: $(date)
Server: $UPSKILL_STAGING_IP
WordPress Path: $UPSKILL_STAGING_PATH
Database: $UPSKILL_STAGING_DB_NAME

Environment Details:
- WordPress Version: $(sshpass -p "$UPSKILL_STAGING_PASS" ssh "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH/public_html && wp core version")
- PHP Version: $(sshpass -p "$UPSKILL_STAGING_PASS" ssh "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "php -v | head -n 1")
- MySQL Version: $(sshpass -p "$UPSKILL_STAGING_PASS" ssh "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "mysql -V")

Backup Contents:
- WordPress files (excluding wp-config.php, cache, etc.)
- Database dump (database.sql)
- Staging wp-config.php (for reference)
EOF

# Create latest symlink
rm -f backups/latest
ln -s "$BACKUP_DIR" backups/latest

echo -e "${GREEN}Staging sync completed successfully!${NC}"
echo "Backup stored in: $BACKUP_DIR"
