<?php
// Background worker: docker pull → compare image ID → rebuild if updated.
// Called via: php docker_pull_worker.php <name> <jobFile> <oldId> <image> <rebuild>
[$name, $jobFile, $oldId, $image, $rebuild] = array_slice($argv, 1, 5);

if (!$name || !$jobFile || !$image) exit(1);

function jw(string $f, array $d): void { file_put_contents($f, json_encode($d)); }

shell_exec('docker pull ' . escapeshellarg($image) . ' 2>&1');

$rawInfo = shell_exec('docker image inspect ' . escapeshellarg($image) . ' 2>/dev/null') ?: '[]';
$info    = json_decode($rawInfo, true) ?: [];
$newId   = $info[0]['Id'] ?? '';

if ($oldId && $newId && $oldId === $newId) {
    jw($jobFile, ['ok' => true, 'status' => 'done', 'updated' => false, 'message' => 'Already up to date']);
    exit;
}

jw($jobFile, ['ok' => true, 'status' => 'rebuilding']);

if ($rebuild && is_executable($rebuild)) {
    exec($rebuild . ' ' . escapeshellarg($name) . ' 2>&1', $out, $rc);
} else {
    exec('docker stop '  . escapeshellarg($name) . ' 2>&1', $o1, $rc1);
    exec('docker start ' . escapeshellarg($name) . ' 2>&1', $o2, $rc2);
    $rc = ($rc1 === 0 && $rc2 === 0) ? 0 : 1;
}

jw($jobFile, $rc === 0
    ? ['ok' => true,  'status' => 'done', 'updated' => true,  'message' => 'Updated and rebuilt']
    : ['ok' => false, 'status' => 'done', 'error'   => 'Rebuild failed after pull']
);
