<?php

namespace App\Provisioning\Steps\Host;

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

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);

        $fqdn = "{$host->name}.{$host->datacenter}.clupilot.net";
        $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();
    }
}
