#!/bin/bash

# Install Dependencies Script for Domain Rotator
# Server: rotator-jago.online (152.42.221.54)

echo "🔧 Installing Dependencies on rotator-jago.online"
echo "=================================================="

# Server details
SERVER_IP="152.42.221.54"
SERVER_USER="root"
SERVER_PASSWORD="gas@1Terus"

# Install dependencies on server
sshpass -p "$SERVER_PASSWORD" ssh "$SERVER_USER@$SERVER_IP" << 'EOF'
    echo "🔄 Starting dependency installation..."
    
    # Update system
    apt update && apt upgrade -y
    
    # Install PHP 8.2 and extensions
    apt install -y software-properties-common
    add-apt-repository ppa:ondrej/php -y
    apt update
    apt install -y php8.2 php8.2-fpm php8.2-mysql php8.2-xml php8.2-curl php8.2-mbstring php8.2-zip php8.2-bcmath php8.2-json php8.2-cli
    
    # Install Composer
    curl -sS https://getcomposer.org/installer | php
    mv composer.phar /usr/local/bin/composer
    chmod +x /usr/local/bin/composer
    
    # Install MySQL
    apt install -y mysql-server
    
    # Install Nginx
    apt install -y nginx
    
    # Install Node.js and npm
    curl -fsSL https://deb.nodesource.com/setup_18.x | bash -
    apt install -y nodejs
    
    # Install other utilities
    apt install -y unzip git curl wget
    
    # Start and enable services
    systemctl start php8.2-fpm
    systemctl enable php8.2-fpm
    systemctl start mysql
    systemctl enable mysql
    systemctl start nginx
    systemctl enable nginx
    
    # Secure MySQL installation
    mysql -e "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'SecureRootPassword123!';"
    mysql -e "DELETE FROM mysql.user WHERE User='';"
    mysql -e "DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');"
    mysql -e "DROP DATABASE IF EXISTS test;"
    mysql -e "DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%';"
    mysql -e "FLUSH PRIVILEGES;"
    
    # Create database and user for Laravel
    mysql -u root -p'SecureRootPassword123!' -e "CREATE DATABASE IF NOT EXISTS domain_rotator;"
    mysql -u root -p'SecureRootPassword123!' -e "CREATE USER IF NOT EXISTS 'domain_rotator'@'localhost' IDENTIFIED BY 'SecurePassword123!';"
    mysql -u root -p'SecureRootPassword123!' -e "GRANT ALL PRIVILEGES ON domain_rotator.* TO 'domain_rotator'@'localhost';"
    mysql -u root -p'SecureRootPassword123!' -e "FLUSH PRIVILEGES;"
    
    echo "✅ Dependencies installed successfully!"
    echo "📋 Installed:"
    echo "   - PHP 8.2 with extensions"
    echo "   - Composer"
    echo "   - MySQL Server"
    echo "   - Nginx"
    echo "   - Node.js & npm"
    echo "   - Database: domain_rotator"
    echo "   - User: domain_rotator"
EOF

echo "✅ Dependencies installation completed!"
