<?php
/**
 * MySQL User Setup Script
 * This script helps set up MySQL users for existing system users
 * Run this script as root to configure MySQL user management
 */

// Check if running as root (alternative method without posix extension)
$current_user = shell_exec('whoami');
if (trim($current_user) !== 'root') {
    die("This script must be run as root\n");
}

// Load configuration to get MYSQL_PASS constant
require_once('/root/whp/web-files/configs/config.php');
require_once('/root/whp/web-files/libs/mysqlmgmt.php');
require_once('/root/whp/web-files/libs/usermgmt.php');

$MySQLMgmt = new mysqlmgmt();
$UserMgmt = new usermgmt();

echo "MySQL User Setup Script\n";
echo "======================\n\n";

// Test MySQL connection
echo "Testing MySQL connection...\n";
$test_result = $MySQLMgmt->testConnection('root', trim(MYSQL_PASS));
if ($test_result['status'] !== '0') {
    echo "ERROR: Cannot connect to MySQL as root. Please check:\n";
    echo "1. MySQL is running\n";
    echo "2. Root password is configured in /root/.my.cnf\n";
    echo "3. MySQL root user has proper privileges\n\n";
    exit(1);
}
echo "✓ MySQL connection successful\n\n";

// Get list of system users
echo "Getting list of system users...\n";
$users = $UserMgmt->list_users();
$hosting_users = [];

foreach ($users as $user) {
    if ($user['uid'] >= 1000 && !$user['protected'] && $user['username'] !== 'root') {
        $hosting_users[] = $user['username'];
    }
}

echo "Found " . count($hosting_users) . " hosting users:\n";
foreach ($hosting_users as $username) {
    echo "- $username\n";
}
echo "\n";

// Ask for confirmation
echo "This script will:\n";
echo "1. Create MySQL users for each hosting user\n";
echo "2. Grant privileges on databases with user prefix\n";
echo "3. Create a default database for each user\n\n";

echo "Do you want to continue? (y/N): ";
$handle = fopen("php://stdin", "r");
$line = fgets($handle);
fclose($handle);

if (trim(strtolower($line)) !== 'y') {
    echo "Setup cancelled.\n";
    exit(0);
}

echo "\nStarting MySQL user setup...\n\n";

$success_count = 0;
$error_count = 0;

foreach ($hosting_users as $username) {
    echo "Processing user: $username\n";
    
    // Generate a random password for MySQL user
    $mysql_password = bin2hex(random_bytes(8));
    
    // Create MySQL user
    $result = $MySQLMgmt->createMySQLUser($username, $mysql_password);
    if ($result['status'] === '0') {
        echo "  ✓ MySQL user created\n";
        
        // Create default database for user
        $db_result = $MySQLMgmt->createDatabase($username, $username);
        if ($db_result['status'] === '0') {
            echo "  ✓ Default database created\n";
            $success_count++;
        } else {
            echo "  ✗ Failed to create default database: " . $db_result['msg'] . "\n";
            $error_count++;
        }
    } else {
        echo "  ✗ Failed to create MySQL user: " . $result['msg'] . "\n";
        $error_count++;
    }
    
    echo "\n";
}

echo "Setup completed!\n";
echo "Successfully processed: $success_count users\n";
echo "Errors: $error_count users\n\n";

if ($success_count > 0) {
    echo "MySQL users have been created with the following privileges:\n";
    echo "- Access to databases with their username prefix (e.g., username_*)\n";
    echo "- Access to their own database (e.g., username)\n";
    echo "- Users can create additional databases and users\n\n";
    
    echo "Users can connect to MySQL using:\n";
    echo "- Host: localhost\n";
    echo "- Port: 3306\n";
    echo "- Username: their system username\n";
    echo "- Password: their system password\n\n";
    
    echo "Note: Users should change their MySQL passwords after first login.\n";
}

echo "\nDone.\n";
?> 