#!/bin/bash
# AUTO TESTER - Automated Installation Script
# This script handles the complete installation process

set -e  # Exit on any error

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

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

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

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

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

# Check if running as root
check_root() {
    if [[ $EUID -eq 0 ]]; then
        print_warning "Running as root is not recommended. Please run as a regular user."
        read -p "Do you want to continue? (y/N): " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            exit 1
        fi
    fi
}

# Check system requirements
check_requirements() {
    print_status "Checking system requirements..."
    
    # Check PHP
    if ! command -v php &> /dev/null; then
        print_error "PHP is not installed. Please install PHP 7.4 or later."
        exit 1
    fi
    
    PHP_VERSION=$(php -r "echo PHP_VERSION;")
    print_success "PHP version: $PHP_VERSION"
    
    # Check MySQL
    if ! command -v mysql &> /dev/null; then
        print_error "MySQL is not installed. Please install MySQL 5.7 or later."
        exit 1
    fi
    
    # Check required PHP extensions
    REQUIRED_EXTENSIONS=("pdo" "pdo_mysql" "json" "mbstring" "curl" "gd" "zip")
    MISSING_EXTENSIONS=()
    
    for ext in "${REQUIRED_EXTENSIONS[@]}"; do
        if ! php -m | grep -q "^$ext$"; then
            MISSING_EXTENSIONS+=("$ext")
        fi
    done
    
    if [ ${#MISSING_EXTENSIONS[@]} -ne 0 ]; then
        print_error "Missing PHP extensions: ${MISSING_EXTENSIONS[*]}"
        print_status "Install them with: sudo apt-get install php-${MISSING_EXTENSIONS[*]}"
        exit 1
    fi
    
    print_success "All requirements met!"
}

# Create database
create_database() {
    print_status "Creating database..."
    
    # Ask for database credentials
    read -p "MySQL username (default: root): " DB_USER
    DB_USER=${DB_USER:-root}
    
    read -s -p "MySQL password: " DB_PASS
    echo
    
    read -p "Database name (default: auto_tester): " DB_NAME
    DB_NAME=${DB_NAME:-auto_tester}
    
    # Test connection
    if ! mysql -u "$DB_USER" -p"$DB_PASS" -e "SELECT 1;" &> /dev/null; then
        print_error "Failed to connect to MySQL. Please check your credentials."
        exit 1
    fi
    
    # Create database if it doesn't exist
    mysql -u "$DB_USER" -p"$DB_PASS" -e "CREATE DATABASE IF NOT EXISTS \`$DB_NAME\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
    
    print_success "Database '$DB_NAME' created successfully!"
    
    # Import database schema
    print_status "Importing database schema..."
    
    # Find the main database file
    DB_FILE=""
    if [ -f "core/database/setup.sql" ]; then
        DB_FILE="core/database/setup.sql"
    elif [ -f "database.sql" ]; then
        DB_FILE="database.sql"
    else
        print_warning "No database schema file found. You may need to import it manually."
        return
    fi
    
    mysql -u "$DB_USER" -p"$DB_PASS" "$DB_NAME" < "$DB_FILE"
    print_success "Database schema imported!"
    
    # Run migrations
    if [ -d "core/database/migrations" ]; then
        print_status "Running database migrations..."
        for migration in core/database/migrations/*.sql; do
            if [ -f "$migration" ]; then
                print_status "Running migration: $(basename "$migration")"
                mysql -u "$DB_USER" -p"$DB_PASS" "$DB_NAME" < "$migration"
            fi
        done
        print_success "All migrations completed!"
    fi
}

# Setup environment file
setup_env() {
    print_status "Setting up environment configuration..."
    
    if [ ! -f ".env.example" ]; then
        print_error ".env.example file not found!"
        exit 1
    fi
    
    # Copy .env.example to .env
    cp .env.example .env
    
    # Update database configuration in .env
    sed -i "s/DB_HOST=localhost/DB_HOST=localhost/" .env
    sed -i "s/DB_NAME=auto_tester/DB_NAME=$DB_NAME/" .env
    sed -i "s/DB_USER=root/DB_USER=$DB_USER/" .env
    
    # Generate random secrets
    JWT_SECRET=$(openssl rand -base64 32 | tr -d "=+/" | cut -c1-32)
    ENCRYPTION_KEY=$(openssl rand -base64 32 | tr -d "=+/" | cut -c1-32)
    CSRF_SECRET=$(openssl rand -base64 32 | tr -d "=+/" | cut -c1-32)
    
    sed -i "s/your_super_secret_key_minimum_32_characters_long/$JWT_SECRET/" .env
    sed -i "s/your_encryption_key_32_chars_minimum/$ENCRYPTION_KEY/" .env
    sed -i "s/your_csrf_secret_32_chars_minimum/$CSRF_SECRET/" .env
    
    print_success "Environment file created and configured!"
    print_warning "Please review and update the .env file with your specific settings."
}

# Setup directories and permissions
setup_directories() {
    print_status "Setting up directories and permissions..."
    
    # Create necessary directories
    DIRECTORIES=("uploads" "storage/logs" "storage/backups" "storage/cache" "storage/sessions")
    
    for dir in "${DIRECTORIES[@]}"; do
        if [ ! -d "$dir" ]; then
            mkdir -p "$dir"
            print_status "Created directory: $dir"
        fi
    done
    
    # Set permissions
    chmod -R 755 uploads/ storage/
    chmod 600 .env
    
    # Set web server writable permissions
    if [ -d "uploads" ]; then
        chmod -R 777 uploads/
    fi
    
    print_success "Directories and permissions set!"
}

# Install npm dependencies (if package.json exists)
install_dependencies() {
    if [ -f "package.json" ] && command -v npm &> /dev/null; then
        print_status "Installing npm dependencies..."
        npm install
        print_success "Dependencies installed!"
    elif [ -f "package.json" ]; then
        print_warning "package.json found but npm is not installed. Please install Node.js and npm."
    fi
}

# Setup web server configuration
setup_webserver() {
    print_status "Setting up web server configuration..."
    
    # Create .htaccess file if it doesn't exist
    if [ ! -f ".htaccess" ]; then
        cat > .htaccess << 'EOF'
# AUTO TESTER - Apache Configuration
RewriteEngine On

# Security headers
<IfModule mod_headers.c>
    Header always set X-Content-Type-Options nosniff
    Header always set X-Frame-Options DENY
    Header always set X-XSS-Protection "1; mode=block"
    Header always set Referrer-Policy "strict-origin-when-cross-origin"
</IfModule>

# Compression
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/css text/javascript application/javascript application/json
</IfModule>

# URL rewriting
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]

# Protect sensitive files
<FilesMatch "\.(env|log|sql|bak|backup)$">
    Require all denied
</FilesMatch>

# Protect .env file
<Files .env>
    Require all denied
</Files>
EOF
        print_success ".htaccess file created!"
    fi
}

# Create backup script
create_backup_script() {
    print_status "Creating backup script..."
    
    cat > scripts/backup.sh << 'EOF'
#!/bin/bash
# AUTO TESTER - Backup Script

DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_DIR="/backups/autotester"
PROJECT_DIR="/path/to/your/project"

# Create backup directory if it doesn't exist
mkdir -p "$BACKUP_DIR"

# Backup database
mysqldump -u root -p auto_tester > "$BACKUP_DIR/db_$DATE.sql"

# Backup files
tar -czf "$BACKUP_DIR/files_$DATE.tar.gz" -C "$PROJECT_DIR" uploads/ storage/

# Delete old backups (older than 30 days)
find "$BACKUP_DIR" -type f -mtime +30 -delete

echo "Backup completed: $DATE"
EOF
    
    chmod +x scripts/backup.sh
    print_success "Backup script created!"
}

# Final checks
final_checks() {
    print_status "Performing final checks..."
    
    # Check if .env file exists
    if [ ! -f ".env" ]; then
        print_error ".env file not found!"
        exit 1
    fi
    
    # Check if database connection works
    if php -r "
    require_once 'core/config.php';
    try {
        \$pdo = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASS);
        echo 'Database connection: OK\n';
    } catch (PDOException \$e) {
        echo 'Database connection: FAILED - ' . \$e->getMessage() . '\n';
        exit(1);
    }
    "; then
        print_success "Database connection test passed!"
    else
        print_error "Database connection test failed!"
        exit 1
    fi
    
    print_success "All checks passed!"
}

# Display completion message
display_completion() {
    echo ""
    echo "==================================="
    echo -e "${GREEN}AUTO TESTER Installation Complete!${NC}"
    echo "==================================="
    echo ""
    echo "Next steps:"
    echo "1. Review and update your .env file"
    echo "2. Configure your web server to point to the 'web' directory"
    echo "3. Set up the backup script in cron: 0 2 * * * /path/to/scripts/backup.sh"
    echo "4. Access the system in your web browser"
    echo ""
    echo "Default admin credentials:"
    echo "Email: admin@autotester.com"
    echo "Password: admin123"
    echo ""
    echo "Documentation: docs/IMPLEMENTATION_GUIDE.md"
    echo "Support: Check the troubleshooting section in the documentation"
    echo ""
}

# Main installation function
main() {
    echo -e "${BLUE}===================================${NC}"
    echo -e "${BLUE}AUTO TESTER Installation${NC}"
    echo -e "${BLUE}===================================${NC}"
    echo ""
    
    check_root
    check_requirements
    create_database
    setup_env
    setup_directories
    install_dependencies
    setup_webserver
    create_backup_script
    final_checks
    display_completion
}

# Run main function
main "$@"
