#!/usr/bin/env php
<?php

declare(strict_types=1);

function log_error(string $message): void
{
    $stderr = fopen('php://stderr', 'w');
    if ($stderr !== false) {
        fwrite($stderr, $message);
        fclose($stderr);
    }
}

function run_setting(array $args): void
{
    $cmd = implode(' ', array_map('escapeshellarg', $args));
    passthru($cmd, $exitCode);

    if ($exitCode !== 0) {
        log_error("steam-autologin: setting failed: {$cmd}\n");
    }
}

function run_background(array $args, string $logFile): void
{
    $cmd = implode(' ', array_map('escapeshellarg', $args));
    passthru($cmd . ' >> ' . escapeshellarg($logFile) . ' 2>&1 &', $exitCode);

    if ($exitCode !== 0) {
        log_error("steam-autologin: background command failed: {$cmd}\n");
    }
}

function run_quiet(array $args): bool
{
    $cmd = implode(' ', array_map('escapeshellarg', $args));
    passthru($cmd . ' >/dev/null 2>&1', $exitCode);
    return $exitCode === 0;
}

function ensure_graphical_environment(): void
{
    $runtimeDir = getenv('XDG_RUNTIME_DIR');
    if ($runtimeDir === false || $runtimeDir === '') {
        $runtimeDir = '/run/user/' . (string) posix_getuid();
        putenv('XDG_RUNTIME_DIR=' . $runtimeDir);
    }

    if ((getenv('WAYLAND_DISPLAY') === false || getenv('WAYLAND_DISPLAY') === '') && file_exists($runtimeDir . '/wayland-0')) {
        putenv('WAYLAND_DISPLAY=wayland-0');
    }

    if (getenv('DISPLAY') === false || getenv('DISPLAY') === '') {
        if (file_exists('/tmp/.X11-unix/X0')) {
            putenv('DISPLAY=:0');
        }
        elseif (file_exists('/tmp/.X11-unix/X1')) {
            putenv('DISPLAY=:1');
        }
    }

    if (getenv('XAUTHORITY') === false || getenv('XAUTHORITY') === '') {
        $gdmAuth = $runtimeDir . '/gdm/Xauthority';
        if (file_exists($gdmAuth)) {
            putenv('XAUTHORITY=' . $gdmAuth);
        }
        else {
            $matches = glob($runtimeDir . '/.mutter-Xwaylandauth.*');
            if (is_array($matches) && isset($matches[0])) {
                putenv('XAUTHORITY=' . $matches[0]);
            }
        }
    }
}

function dismiss_gnome_overview(): void
{
    if (!run_quiet(['which', 'gdbus'])) {
        return;
    }

    $cmd = implode(' ', [
        'gdbus',
        'call',
        '--session',
        '--dest', 'org.gnome.Shell',
        '--object-path', '/org/gnome/Shell',
        '--method', 'org.freedesktop.DBus.Properties.Set',
        'org.gnome.Shell',
        'OverviewActive',
        "'<false>'",
    ]);
    passthru($cmd . ' >/dev/null 2>&1', $exitCode);
    if ($exitCode !== 0) {
        log_error("steam-autologin: failed to close GNOME Overview via DBus\n");
    }
}
function focus_big_picture(): bool
{
    for ($i = 0; $i < 60; $i++) {
        run_quiet(['wmctrl', '-r', ':ACTIVE:', '-b', 'remove,fullscreen']);

        foreach (['Steam Big Picture Mode', 'Big-Picture-Modus'] as $title) {
            if (run_quiet(['wmctrl', '-r', $title, '-b', 'add,fullscreen'])
                && run_quiet(['wmctrl', '-a', $title])) {
                run_quiet(['wmctrl', '-c', 'Remote Desktop']);
                return true;
            }
        }

        sleep(1);
    }

    log_error("steam-autologin: Steam Big Picture window was not found/focused\n");
    return false;
}

$settings = [
    ['gsettings', 'set', 'org.gnome.desktop.screensaver', 'lock-enabled', 'false'],
    ['gsettings', 'set', 'org.gnome.desktop.lockdown', 'disable-lock-screen', 'true'],
    ['gsettings', 'set', 'org.gnome.desktop.session', 'idle-delay', 'uint32 0'],
    ['gsettings', 'set', 'org.gnome.settings-daemon.plugins.power', 'sleep-inactive-ac-type', 'nothing'],
    ['gsettings', 'set', 'org.gnome.settings-daemon.plugins.power', 'sleep-inactive-battery-type', 'nothing'],
];

foreach ($settings as $setting) {
    run_setting($setting);
}

ensure_graphical_environment();

$steamCommand = array_merge(['steam', '-gamepadui'], array_slice($argv, 1));
run_background($steamCommand, '/tmp/steam-autologin-steam.log');

sleep(3);
dismiss_gnome_overview();
focus_big_picture();
dismiss_gnome_overview();
exit(0);
