#!/usr/bin/env python3

from __future__ import annotations

import json
import subprocess
from datetime import UTC, datetime


def run(command: list[str]) -> tuple[int, str]:
    completed = subprocess.run(
        command,
        check=False,
        capture_output=True,
        text=True,
        timeout=15,
    )

    return completed.returncode, completed.stdout.strip()


def service_state(unit: str) -> dict[str, object]:
    _, enabled = run(
        ["systemctl", "is-enabled", unit]
    )
    _, active = run(
        ["systemctl", "is-active", unit]
    )

    return {
        "enabled": enabled,
        "active": active,
        "status": (
            "OK"
            if enabled == "enabled"
            and active == "active"
            else "FAILED"
        ),
    }


def ssh_hardening() -> dict[str, object]:
    _, output = run(["sshd", "-T"])

    values: dict[str, str] = {}

    wanted = {
        "permitrootlogin",
        "passwordauthentication",
        "pubkeyauthentication",
        "authenticationmethods",
        "maxauthtries",
        "maxsessions",
        "logingracetime",
        "x11forwarding",
        "allowagentforwarding",
        "allowtcpforwarding",
    }

    for line in output.splitlines():
        key, _, value = line.partition(" ")

        if key in wanted:
            values[key] = value.strip()

    expected = {
        "permitrootlogin": {
            "without-password",
            "prohibit-password",
        },
        "passwordauthentication": {"no"},
        "pubkeyauthentication": {"yes"},
        "authenticationmethods": {"publickey"},
        "maxauthtries": {"3"},
        "maxsessions": {"4"},
        "logingracetime": {"30"},
        "x11forwarding": {"no"},
        "allowagentforwarding": {"no"},
        "allowtcpforwarding": {"no"},
    }

    matches = {
        key: values.get(key) in allowed
        for key, allowed in expected.items()
    }

    return {
        "status": (
            "OK"
            if all(matches.values())
            else "FAILED"
        ),
        "values": values,
        "matches": matches,
    }


def firewall_state() -> dict[str, object]:
    _, ipv4 = run(["iptables", "-S", "FIVEBR-WINGS"])
    _, ipv6 = run(["ip6tables", "-S", "FIVEBR-WINGS"])

    ipv4_required = (
        "-A FIVEBR-WINGS "
        "-s 37.125.109.91/32 "
        "-p tcp -m tcp --dport 8080 -j ACCEPT"
    )

    ipv4_drop = (
        "-A FIVEBR-WINGS "
        "-p tcp -m tcp --dport 8080 -j DROP"
    )

    ipv6_drop = (
        "-A FIVEBR-WINGS "
        "-p tcp -m tcp --dport 8080 -j DROP"
    )

    checks = {
        "ipv4_core01_accept": ipv4_required in ipv4,
        "ipv4_public_drop": ipv4_drop in ipv4,
        "ipv6_public_drop": ipv6_drop in ipv6,
    }

    return {
        "status": (
            "OK"
            if all(checks.values())
            else "FAILED"
        ),
        "checks": checks,
    }


def fail2ban_state() -> dict[str, object]:
    service = service_state("fail2ban.service")

    code, status = run(
        [
            "fail2ban-client",
            "status",
            "5ibr-wings-sftp",
        ]
    )

    jail_present = code == 0

    return {
        "status": (
            "OK"
            if service["status"] == "OK"
            and jail_present
            else "FAILED"
        ),
        "service": service,
        "jail_present": jail_present,
    }


def listening_ports() -> dict[str, object]:
    _, output = run(["ss", "-lntup"])

    ports = {
        "22": ":22 ",
        "2022": ":2022 ",
        "8080": ":8080 ",
    }

    checks = {
        name: marker in output
        for name, marker in ports.items()
    }

    return {
        "status": (
            "OK"
            if all(checks.values())
            else "FAILED"
        ),
        "checks": checks,
    }


def main() -> int:
    result = {
        "schema_version": 1,
        "generated_at": datetime.now(UTC).isoformat(),
        "hostname": "vmi3374884",
        "ssh_hardening": ssh_hardening(),
        "wings_firewall": firewall_state(),
        "fail2ban": fail2ban_state(),
        "wings_service": service_state("wings.service"),
        "docker_service": service_state("docker.service"),
        "listening_ports": listening_ports(),
    }

    statuses = [
        value.get("status")
        for key, value in result.items()
        if isinstance(value, dict)
        and "status" in value
    ]

    result["overall_status"] = (
        "HEALTHY"
        if statuses
        and all(status == "OK" for status in statuses)
        else "FAILED"
    )

    print(
        json.dumps(
            result,
            ensure_ascii=False,
            separators=(",", ":"),
        )
    )

    return (
        0
        if result["overall_status"] == "HEALTHY"
        else 1
    )


if __name__ == "__main__":
    raise SystemExit(main())
