#!/usr/bin/env python3

import subprocess
import re
import os


def run(cmd):
    try:
        return subprocess.check_output(
            cmd,
            shell=True,
            text=True,
            stderr=subprocess.DEVNULL
        ).strip()
    except Exception:
        return ""


# ---------------------------------------------------------
# Proxmox Version
# ---------------------------------------------------------

px_version = run("pveversion")


# ---------------------------------------------------------
# VMs
# ---------------------------------------------------------

qm_list = run("qm list")
lines = qm_list.splitlines()

# Header entfernen
vm_lines = lines[1:] if len(lines) > 1 else []

px_vms_sum = len(vm_lines)
px_vms_started = sum(1 for l in vm_lines if "running" in l.lower())
px_vms_stopped = sum(1 for l in vm_lines if "stopped" in l.lower())


# ---------------------------------------------------------
# Updates
# ---------------------------------------------------------

apt_out = run("apt list --upgradable 2>/dev/null")

updates = apt_out.splitlines()[1:] if apt_out else []

supdates = sum(1 for l in updates if "security" in l.lower())
nupdates = len(updates) - supdates


# ---------------------------------------------------------
# Kernel / Reboot
# ---------------------------------------------------------

kernel = run("uname -r")

latest_kernel = run(
    "ls -t /boot/vmlinuz-* 2>/dev/null | head -n1"
).replace("/boot/vmlinuz-", "")

reboot = 0

if os.path.exists("/var/run/reboot-required"):
    reboot = 1

if kernel and latest_kernel and kernel != latest_kernel:
    reboot = 1


# ---------------------------------------------------------
# Netzwerk
# ---------------------------------------------------------

iface = run(
    "ip route | awk '/default/ {print $5; exit}'"
)

ip_addr = run(
    f"ip -4 addr show {iface} | awk '/inet / {{print $2}}' | cut -d/ -f1"
)

gateway = run(
    "ip route | awk '/default/ {print $3; exit}'"
)


# ---------------------------------------------------------
# Sensors
# ---------------------------------------------------------

sensor_out = run("sensors")
perfdata = []

prefix = ""

for raw_line in sensor_out.splitlines():

    line = raw_line.strip()

    if not line:
        continue

    # Adapter-Zeilen ignorieren
    if line.startswith("Adapter:"):
        continue

    # Klammer-/Infozeilen ignorieren
    if line.startswith("("):
        continue

    # Chipnamen erkennen
    if ":" not in line and "°C" not in line:
        prefix = re.sub(r"[^A-Za-z0-9_-]", "_", line)
        continue

    # Nur Temperaturzeilen verarbeiten
    if "°C" not in line:
        continue

    if ":" not in line:
        continue

    key, values = line.split(":", 1)

    key = key.strip()

    # Sensorname säubern
    key = re.sub(r"\s+", "_", key)
    key = re.sub(r"[^A-Za-z0-9_-]", "", key)

    # Problematische Sensoren ignorieren
    if key in ["PECIAgent1", "AUXTIN"]:
        continue

    # Temperaturwert extrahieren
    val_match = re.search(r"[-+]?\d+(\.\d+)?", values)

    if not val_match:
        continue

    value = val_match.group(0)

    metric = f"{prefix}-{key}"

    # Final säubern
    metric = re.sub(r"[^A-Za-z0-9_-]", "_", metric)

    # Doppelte Unterstriche reduzieren
    metric = re.sub(r"_+", "_", metric)

    perfdata.append(
        f"{metric}={value};100;120"
    )


# Local Check Output
if perfdata:
    temp_output = "P Proxmox_LMsensors " + "|".join(perfdata)
else:
    temp_output = "0 Proxmox_LMsensors - Keine Sensordaten gefunden"


# ---------------------------------------------------------
# Patchstatus
# ---------------------------------------------------------

patch_status = 0

if reboot > 0:
    patch_status = 1

if supdates > 0:
    patch_status = 2


# ---------------------------------------------------------
# Output
# ---------------------------------------------------------

print(
    f"0 Proxmox_Version "
    f"Version={px_version} "
    f"- Version OK"
)

print(
    f"0 Proxmox_VMs "
    f"Started={px_vms_started}|"
    f"Stopped={px_vms_stopped}|"
    f"Total={px_vms_sum} "
    f"- {px_vms_started} von {px_vms_sum} VMs laufen"
)

print(temp_output)

print(
    f"0 Proxmox_Network "
    f"- IP: {ip_addr}, "
    f"Gateway: {gateway}, "
    f"Interface: {iface}"
)

print(
    f"{patch_status} Proxmox-Patchstatus "
    f"SecurityUpdates={supdates}|"
    f"RegularUpdates={nupdates}|"
    f"Reboot={reboot} "
    f"- Security: {supdates}, "
    f"Updates: {nupdates}, "
    f"Reboot: {reboot}"
)