summaryrefslogtreecommitdiff
path: root/src/Module/Modules/UserModule.php
blob: 1749b58612f9cd3cac15909a941f9879dbff0f50 (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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php

namespace PHPIAC\Module\Modules;

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

class UserModule implements ModuleInterface
{
    /**
     * UserModule constructor.
     *
     * @param string $name
     * @param array $options
     * @param string $state
     */
    public function __construct(
        private string $name,
        private array $options = [],
        private string $state = State::PRESENT
    ) {
        $this->options = array_replace([
            'append' => false,
            'create_home' => true,
            'groups' => [],
            'shell' => '/bin/bash',
        ], $options);
    }

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

        $ssh->exec("cat /etc/passwd | grep $this->name:");
        $hasUser = $ssh->read();

        $state = match ($this->state) {
            State::PRESENT => str_starts_with($hasUser, "$this->name:"),
            State::ABSENT => empty($hasUser),
        };

        $ssh->disablePTY();

        return $state;
    }

    /**
     * @inheritDoc
     */
    public function getCommands(): array
    {
        return match ($this->state) {
            State::PRESENT => [
                "sudo adduser $this->name --quiet" .
                    " --shell " . $this->options['shell'] .
                    ($this->options['create_home'] ? '' : ' --no-create-home'),
                "sudo usermod -" . ($this->options['append'] ? 'a' : '') . "G " . implode(',', $this->options['groups']) . " $this->name"
            ],
            State::ABSENT => [
                "sudo apt remove -y $this->package",
            ],
        };
    }
}