<?php

namespace PHPIAC\Modules;

use PHPIAC\Connection;
use PHPIAC\Module\Module;
use PHPIAC\Module\State;

class UfwModule extends Module
{
    protected string $rule;
    protected string $name;

    protected string $state = State::ENABLED;

    /**
     * @inheritDoc
     */
    public function checkState(): bool
    {
        $state = false;

        Connection::enablePty();

        Connection::exec('sudo ufw status');
        $status = Connection::read();

        if ($this->state === State::ENABLED) {
            $rule = strtoupper($this->rule);
            Connection::exec("sudo ufw status | grep '$this->name\|$rule'");
            $statusGrep = Connection::read();

            $state =
                str_contains($status, 'Status: active') &&
                str_contains($statusGrep, $this->name) && str_contains($statusGrep, $rule);
        }
        else if ($this->state === State::DISABLED) {
            $state = str_contains($status, 'Status: inactive');
        }

        Connection::disablePty();

        return $state;
    }

    /**
     * @inheritDoc
     */
    public function execute(): void
    {
        Connection::exec(implode(PHP_EOL, [
            "sudo ufw $this->rule $this->name",
            match ($this->state) {
                State::ENABLED => "sudo ufw --force enable",
                State::DISABLED => "sudo ufw disable",
            },
        ]));
    }
}