summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/AptModule.php54
-rw-r--r--src/UserModule.php70
2 files changed, 124 insertions, 0 deletions
diff --git a/src/AptModule.php b/src/AptModule.php
new file mode 100644
index 0000000..9b882e8
--- /dev/null
+++ b/src/AptModule.php
@@ -0,0 +1,54 @@
+<?php
+
+namespace PHPIAC\Modules;
+
+use PHPIAC\Module\Module;
+use PHPIAC\Module\State;
+use phpseclib3\Net\SSH2;
+
+class AptModule extends Module
+{
+ /**
+ * 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"],
+ };
+ }
+}
diff --git a/src/UserModule.php b/src/UserModule.php
new file mode 100644
index 0000000..fcab5a8
--- /dev/null
+++ b/src/UserModule.php
@@ -0,0 +1,70 @@
+<?php
+
+namespace PHPIAC\Modules;
+
+use PHPIAC\Module\Module;
+use PHPIAC\Module\State;
+use phpseclib3\Net\SSH2;
+
+class UserModule extends Module
+{
+ /**
+ * UserModule constructor.
+ *
+ * @param string $username
+ * @param array $options
+ * @param string $state
+ */
+ public function __construct(
+ private string $username,
+ 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->username:");
+ $hasUser = $ssh->read();
+
+ $state = match ($this->state) {
+ State::PRESENT => str_starts_with($hasUser, "$this->username:"),
+ State::ABSENT => empty($hasUser),
+ };
+
+ $ssh->disablePTY();
+
+ return $state;
+ }
+
+ /**
+ * @inheritDoc
+ */
+ public function getCommands(): array
+ {
+ return match ($this->state) {
+ State::PRESENT => [
+ "sudo adduser $this->username --quiet" .
+ " --shell " . $this->options['shell'] .
+ ($this->options['create_home'] ? '' : ' --no-create-home'),
+ "sudo usermod -" . ($this->options['append'] ? 'a' : '') . "G " . implode(',', $this->options['groups']) . " $this->username"
+ ],
+ State::ABSENT => [
+ "sudo userdel $this->username",
+ ],
+ };
+ }
+}