<?php

namespace App\Provisioning\Steps\Host;

use App\Models\ProvisioningRun;
use App\Provisioning\StepResult;
use App\Services\Ssh\RemoteShell;
use App\Support\HostName;

class PrepareBaseSystem extends HostStep
{
    public function __construct(private RemoteShell $shell) {}

    public function key(): string
    {
        return 'prepare_base_system';
    }

    public function execute(ProvisioningRun $run): StepResult
    {
        $host = $this->host($run);
        $this->keyLogin($this->shell, $host);

        // Derselbe FQDN, den DNS führt und den die Bootstrap-Zeile mitgibt.
        // Hier stand `{$host->name}.{$host->datacenter}.clupilot.net` — eine
        // Domain, die im ganzen Repo sonst nirgends vorkommt und in keiner
        // Konfiguration steht. Die Maschine trug damit einen dritten Namen im
        // eigenen /etc/hosts.
        $fqdn = HostName::fqdn($host->name);
        $hostsLine = "{$host->public_ip} {$fqdn} {$host->name}";

        $commands = [
            'hostnamectl set-hostname '.escapeshellarg($host->name),
            'grep -q '.escapeshellarg($fqdn).' /etc/hosts || echo '.escapeshellarg($hostsLine).' >> /etc/hosts',
            'export DEBIAN_FRONTEND=noninteractive; apt-get update',
            'export DEBIAN_FRONTEND=noninteractive; apt-get install -y curl gnupg ifupdown2 chrony',
        ];

        foreach ($commands as $command) {
            if (! $this->shell->run($command)->ok()) {
                return StepResult::retry(30, 'base system preparation failed');
            }
        }

        return StepResult::advance();
    }
}
