summaryrefslogtreecommitdiff
path: root/src/Module/Modules/AptModule.php
blob: ccf48927ac98bdc0f7233e337c6f25c61115b2e3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?php

namespace PHPIAC\Module\Modules;

use PHPIAC\Module\ModuleInterface;
use PHPIAC\Module\State;
use phpseclib3\Net\SSH2;

class AptModule implements ModuleInterface
{
    /**
     * AptModule constructor.
     *
     * @param string $package
     * @param string $state
     */
    public function __construct(
        private string $package,
        private string $state = State::PRESENT
    ) {}

    /**
     * @inheritDoc
     */
    public function checkState(): bool
    {
        global $ssh;
        /**@var SSH2 $ssh*/
        $ssh->enablePTY();

        $ssh->exec("dpkg -l $this->package | grep 'ii'");
        $dpkg = $ssh->read();

        $state = match ($this->state) {
            State::PRESENT => str_starts_with($dpkg, 'ii'),
            State::ABSENT => str_contains($dpkg, 'no packages found'),
        };

        $ssh->disablePTY();

        return $state;
    }

    /**
     * @inheritDoc
     */
    public function getCommands(): array
    {
        return match ($this->state) {
            State::PRESENT => ["sudo apt install -y $this->package"],
            State::ABSENT => ["sudo apt remove -y $this->package"],
        };
    }
}