<?php
// Adminer SSO Integration - Similar to phpMyAdmin SSO
// This script provides seamless single sign-on to Adminer using WHP authentication

// Check if user is authenticated
if (!defined('AUTH_USER')) {
    header('Location: login.php');
    exit();
}

require_once('libs/pgsqlmgmt.php');
$pgsqlMgmt = new pgsqlmgmt();

// Get PostgreSQL credentials
$pgUser = AUTH_USER;
$pgPassword = '';

// For root user, use the postgres superuser
if (AUTH_USER === 'root' || AUTH_USER === 'whp') {
    $pgUser = 'postgres';
    // Get password from .pgpass
    if (file_exists('/root/.pgpass')) {
        $pgpass_content = shell_exec('cat /root/.pgpass | head -1');
        if ($pgpass_content) {
            $pgpass_parts = explode(':', trim($pgpass_content));
            if (count($pgpass_parts) >= 5) {
                $pgPassword = $pgpass_parts[4];
            }
        }
    }
} else {
    // For regular users, get their PostgreSQL credentials
    $pgUser = AUTH_USER . '_pg';
    
    // First try to get stored password
    require_once('/docker/whp/web/libs/usermgmt.php');
    $UserMgmt = new usermgmt();
    $pgPassword = $UserMgmt->getUserPostgreSQLPassword(AUTH_USER);
    
    if (!$pgPassword) {
        // Check if user exists in PostgreSQL
        $userExists = $pgsqlMgmt->checkUserExists($pgUser);
        
        if (!$userExists['exists']) {
            // Create PostgreSQL user for this system user
            $pgPassword = bin2hex(random_bytes(12)); // Generate secure password
            
            // Use restricted method for regular users, full method for root/whp
            if (AUTH_USER === 'root' || AUTH_USER === 'whp') {
                $result = $pgsqlMgmt->createPostgreSQLUser($pgUser, $pgPassword);
            } else {
                $result = $pgsqlMgmt->createPostgreSQLUserForSSO($pgUser, $pgPassword);
            }
            
            if ($result['status'] !== '0') {
                // If user creation fails, redirect to error page
                header("Location: postgresql-password-entry.php?error=" . urlencode($result['msg']));
                exit;
            }
            
            // Store password for SSO integration
            $UserMgmt->setUserPostgreSQLPassword(AUTH_USER, $pgPassword);
        } else {
            // For existing users, check if password is stored in session (from password entry form)
            session_start();
            if (isset($_SESSION['postgresql_password_' . AUTH_USER])) {
                $pgPassword = $_SESSION['postgresql_password_' . AUTH_USER];
                // Clear the session password for security
                unset($_SESSION['postgresql_password_' . AUTH_USER]);
                // Store it for future use
                $UserMgmt->setUserPostgreSQLPassword(AUTH_USER, $pgPassword);
            } else {
                // If we can't get the password, redirect to a password entry form
                header("Location: postgresql-password-entry.php");
                exit;
            }
        }
    }
}
?>

<html>
    <body>
        <div>Logging into Adminer...</div>
        <form id="adminer_login" action="adminer.php" method="post">
            <input type="hidden" name="auth[driver]" value="pgsql">
            <input type="hidden" name="auth[server]" value="localhost:5432">
            <input type="hidden" name="auth[username]" value="<?php echo trim($pgUser); ?>">
            <input type="hidden" name="auth[password]" value="<?php echo trim($pgPassword); ?>">
            <input type="hidden" name="auth[db]" value="">
        </form>
        <script type="text/javascript">document.getElementById('adminer_login').submit();</script>  
    </body>
</html>