<?php
// /docker/whp/web/libs/docker.php
// Safe docker invocation: array argv via proc_open, no shell string concat.

function whp_docker(array $argv): array {
    $descriptors = [
        0 => ['pipe', 'r'],
        1 => ['pipe', 'w'],
        2 => ['pipe', 'w'],
    ];
    $cmd = array_merge(['docker'], $argv);
    $proc = proc_open($cmd, $descriptors, $pipes);
    if (!is_resource($proc)) {
        return ['rc' => -1, 'stdout' => '', 'stderr' => 'proc_open failed'];
    }
    fclose($pipes[0]);
    $stdout = stream_get_contents($pipes[1]);
    $stderr = stream_get_contents($pipes[2]);
    fclose($pipes[1]); fclose($pipes[2]);
    $rc = proc_close($proc);
    return ['rc' => $rc, 'stdout' => $stdout, 'stderr' => $stderr];
}

function whp_docker_label(string $container, string $key): string {
    $r = whp_docker(['inspect', '-f', '{{ index .Config.Labels "' . $key . '" }}', $container]);
    return trim($r['stdout'] ?? '');
}
