#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
CyberPanel Security Shield & CPU Guard Engine
Provides:
1. Deep Server Malware & Rootkit Scanner (Processes, memfd/deleted, /proc bind-mounts,
   UID=0 rogue root accounts, systemd generators/services, udev rules, cron jobs, SUIDs, C2 connections)
2. One-click & Automatic Threat Remediation (chattr -ia, unmount, kill -9, file removal, user cleanup)
3. CPU Guard (Prevents 100% CPU saturation by dynamically renicing/throttling runaway processes,
   limiting per-user lsphp concurrency, and enforcing CPUQuota on heavy services)
4. Routine Cron Automation (Runs every 3 minutes via /etc/cron.d/cyberpanel-security-guard)
"""

import os
import sys
import pwd
import time
import json
import glob
import shutil
import signal
import subprocess
from datetime import datetime

DATA_DIR = "/usr/local/CyberCP/securityGuardData"
CONFIG_FILE = os.path.join(DATA_DIR, "config.json")
LOG_FILE = os.path.join(DATA_DIR, "events.json")
LAST_SCAN_FILE = os.path.join(DATA_DIR, "last_scan.json")
CRON_FILE = "/etc/cron.d/cyberpanel-security-guard"

DEFAULT_CONFIG = {
    "auto_remediate": True,
    "cron_enabled": True,
    "cpu_guard_enabled": True,
    "max_cpu_threshold": 85.0,
    "per_process_cpu_limit": 75.0,
    "max_lsphp_per_user": 12,
    "kill_unknown_high_cpu": True,
    "elasticsearch_heap_mb": 512,
    "updated_at": ""
}

KNOWN_MALWARE_SIGNATURES = [
    "gs-dbus", "defunct", "systemd-idmap-agent", "systemd-pcrphase-ext",
    "systemd-pcrphase-net", "systemd-coredumpd-archive", "systemd-timesyncd-nts",
    "systemd-homed-reaper", "systemd-userdb-cache", "atd-batch", "chronyd-nts",
    "dnsmasq-leasectl", "ntpdate-pool", "rsyslogd-impstats", "smartd-attributes",
    "sshd-legacy-keys", "systemd-route-policy-generator", "systemd-network-slice-generator",
    "dbus-socket-helper", "system-event-processor", "system-storage-manager",
    "69-dev-random-init.rules", "73-input-device-sync.rules", ".gsusr-",
    "api.githubresource.com", "trycloudflare.com/api/quickwin", "xmrig", "kinsing",
    "kdevtmpfsi", "Sustes", "raid5wq"
]

KNOWN_MALWARE_PATHS = [
    "/usr/bin/gs-dbus",
    "/usr/bin/defunct",
    "/usr/sbin/colord",
    "/etc/cron.d/.colord",
    "/etc/udev/rules.d/69-dev-random-init.rules",
    "/etc/udev/rules.d/73-input-device-sync.rules",
    "/lib/systemd/system/gs-dbus.service",
    "/lib/systemd/system/gs-dbus.dat",
    "/lib/systemd/system/defunct.service",
    "/lib/systemd/system/defunct.dat",
    "/lib/systemd/system/dbus-socket-helper.service",
    "/lib/systemd/system/system-event-processor.service",
    "/lib/systemd/system/system-event-processor.timer",
    "/lib/systemd/system/system-storage-manager.service",
    "/lib/systemd/system/system-storage-manager.timer",
    "/lib/systemd/system-generators/systemd-route-policy-generator",
    "/lib/systemd/system-generators/systemd-network-slice-generator",
    "/lib/systemd/systemd-coredumpd-archive",
    "/lib/systemd/systemd-idmap-agent",
    "/lib/systemd/systemd-pcrphase-ext",
    "/lib/systemd/systemd-pcrphase-net",
    "/lib/systemd/systemd-timesyncd-nts",
    "/usr/sbin/atd-batch",
    "/usr/sbin/chronyd-nts",
    "/usr/sbin/dnsmasq-leasectl",
    "/usr/sbin/ntpdate-pool",
    "/usr/sbin/rsyslogd-impstats",
    "/usr/sbin/smartd-attributes",
    "/usr/sbin/sshd-legacy-keys",
    "/usr/sbin/systemd-homed-reaper",
    "/usr/sbin/systemd-userdb-cache"
]

SAFE_SYSTEM_BINARIES = (
    "/usr/local/CyberCP", "/usr/local/lsws", "/usr/sbin/mariadbd", "/usr/share/elasticsearch",
    "/usr/bin/redis-server", "/usr/sbin/pdns_server", "/usr/sbin/dovecot", "/usr/lib/postfix",
    "/usr/sbin/pure-ftpd", "/usr/sbin/opendkim", "/usr/bin/nghttpx", "/usr/local/lsmcd",
    "/lib/systemd/systemd", "/usr/lib/systemd/systemd", "/usr/bin/dbus-daemon", "/usr/sbin/cron",
    "/usr/sbin/rsyslogd", "/usr/sbin/sshd", "/usr/bin/python", "/usr/bin/fail2ban",
    "/opt/imunify360", "/usr/sbin/imunify", "/usr/bin/udevadm"
)


def ensure_data_dir():
    if not os.path.exists(DATA_DIR):
        os.makedirs(DATA_DIR, mode=0o755, exist_ok=True)


def load_config():
    ensure_data_dir()
    cfg = dict(DEFAULT_CONFIG)
    if os.path.exists(CONFIG_FILE):
        try:
            with open(CONFIG_FILE, "r", encoding="utf-8") as f:
                saved = json.load(f)
                cfg.update(saved)
        except Exception:
            pass
    return cfg


def save_config(new_cfg):
    ensure_data_dir()
    cfg = load_config()
    cfg.update(new_cfg)
    cfg["updated_at"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    with open(CONFIG_FILE, "w", encoding="utf-8") as f:
        json.dump(cfg, f, indent=2)
    sync_cron_file(cfg.get("cron_enabled", True))
    return cfg


def sync_cron_file(enabled=True):
    if enabled:
        content = (
            "SHELL=/bin/bash\n"
            "PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin\n"
            "*/3 * * * * root /usr/bin/python3 /usr/local/CyberCP/firewall/security_guard.py --cron >/dev/null 2>&1\n"
        )
        try:
            with open(CRON_FILE, "w", encoding="utf-8") as f:
                f.write(content)
            os.chmod(CRON_FILE, 0o644)
        except Exception:
            pass
    else:
        if os.path.exists(CRON_FILE):
            try:
                os.remove(CRON_FILE)
            except Exception:
                pass


def append_event(event_type, severity, title, details, action_taken=""):
    ensure_data_dir()
    events = []
    if os.path.exists(LOG_FILE):
        try:
            with open(LOG_FILE, "r", encoding="utf-8") as f:
                events = json.load(f)
        except Exception:
            events = []
    event = {
        "time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "type": event_type,
        "severity": severity,
        "title": title,
        "details": details,
        "action": action_taken
    }
    events.insert(0, event)
    events = events[:150]
    try:
        with open(LOG_FILE, "w", encoding="utf-8") as f:
            json.dump(events, f, indent=2)
    except Exception:
        pass


def get_events():
    if os.path.exists(LOG_FILE):
        try:
            with open(LOG_FILE, "r", encoding="utf-8") as f:
                return json.load(f)
        except Exception:
            return []
    return []


def run_cmd(cmd, timeout=10):
    try:
        res = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                             text=True, timeout=timeout)
        return res.stdout.strip()
    except Exception:
        return ""


def get_system_metrics():
    # CPU usage from /proc/stat
    cpu_pct = 0.0
    try:
        with open("/proc/stat", "r") as f:
            l1 = [int(x) for x in f.readline().split()[1:8]]
        time.sleep(0.25)
        with open("/proc/stat", "r") as f:
            l2 = [int(x) for x in f.readline().split()[1:8]]
        idle1, idle2 = l1[3] + l1[4], l2[3] + l2[4]
        tot1, tot2 = sum(l1), sum(l2)
        diff_tot = tot2 - tot1
        diff_idle = idle2 - idle1
        if diff_tot > 0:
            cpu_pct = round(100.0 * (diff_tot - diff_idle) / diff_tot, 1)
    except Exception:
        pass

    # Load average
    load_avg = [0.0, 0.0, 0.0]
    try:
        load_avg = [round(x, 2) for x in os.getloadavg()]
    except Exception:
        pass

    # RAM usage
    mem_total = 0
    mem_avail = 0
    try:
        with open("/proc/meminfo", "r") as f:
            for line in f:
                if line.startswith("MemTotal:"):
                    mem_total = int(line.split()[1]) // 1024
                elif line.startswith("MemAvailable:"):
                    mem_avail = int(line.split()[1]) // 1024
    except Exception:
        pass
    mem_used = max(0, mem_total - mem_avail)
    mem_pct = round(100.0 * mem_used / mem_total, 1) if mem_total > 0 else 0.0

    # Top processes
    top_procs = []
    out = run_cmd("ps -eo pid,user,pcpu,pmem,ni,comm,args --sort=-pcpu | head -n 12")
    lines = out.splitlines()
    for line in lines[1:]:
        parts = line.strip().split(None, 6)
        if len(parts) >= 6:
            top_procs.append({
                "pid": int(parts[0]),
                "user": parts[1],
                "cpu": float(parts[2]),
                "mem": float(parts[3]),
                "nice": parts[4],
                "comm": parts[5],
                "args": parts[6][:120] if len(parts) > 6 else parts[5]
            })

    return {
        "cpu_percent": cpu_pct,
        "load_avg": load_avg,
        "mem_total_mb": mem_total,
        "mem_used_mb": mem_used,
        "mem_avail_mb": mem_avail,
        "mem_percent": mem_pct,
        "cpu_cores": os.cpu_count() or 1,
        "top_processes": top_procs
    }


def scan_server():
    threats = []

    # 1. Check /proc bind mounts hiding processes
    try:
        with open("/proc/mounts", "r") as f:
            for line in f:
                parts = line.split()
                if len(parts) >= 2 and parts[1].startswith("/proc/") and parts[1][6:].isdigit():
                    pid = parts[1][6:]
                    threats.append({
                        "id": f"proc_mount_{pid}",
                        "category": "Hidden Process (/proc mount)",
                        "severity": "CRITICAL",
                        "target": parts[1],
                        "pid": int(pid),
                        "description": f"Process PID {pid} is masked via mount --bind over {parts[1]}"
                    })
    except Exception:
        pass

    # 2. Check running processes for memfd, deleted binaries, spoofed kernel names, or known malware paths
    for pdir in glob.glob("/proc/[0-9]*"):
        pid_str = os.path.basename(pdir)
        if not pid_str.isdigit():
            continue
        pid = int(pid_str)
        try:
            exe = os.readlink(os.path.join(pdir, "exe"))
        except Exception:
            continue

        cmdline = ""
        try:
            with open(os.path.join(pdir, "cmdline"), "rb") as f:
                cmdline = f.read().replace(b"\x00", b" ").decode("utf-8", errors="ignore").strip()
        except Exception:
            pass

        is_malicious = False
        reason = ""

        if "/memfd:" in exe or exe.startswith("/tmp/") or exe.startswith("/var/tmp/") or exe.startswith("/dev/shm/"):
            is_malicious = True
            reason = f"Fileless/temp execution detected: {exe}"
        elif any(sig in exe or sig in cmdline for sig in KNOWN_MALWARE_SIGNATURES):
            is_malicious = True
            reason = f"Matches known malware signature ({exe})"
        elif cmdline.startswith("[") and "]" in cmdline and exe:
            # Real kernel threads have no /proc/pid/exe symlink! Any user process with [kworker] etc. and an exe is spoofing!
            is_malicious = True
            reason = f"Userland process spoofing Linux kernel thread '{cmdline}' -> {exe}"

        if is_malicious:
            clean_exe = exe.replace(" (deleted)", "")
            threats.append({
                "id": f"proc_{pid}",
                "category": "Malicious Process",
                "severity": "CRITICAL",
                "target": clean_exe,
                "pid": pid,
                "description": f"PID {pid} ({cmdline[:60]}): {reason}"
            })

    # 3. Check known malware file paths & clones by exact known byte sizes in /usr/sbin and /lib/systemd
    for mpath in KNOWN_MALWARE_PATHS:
        if os.path.exists(mpath):
            threats.append({
                "id": f"file_{mpath}",
                "category": "Backdoor File / Service",
                "severity": "CRITICAL",
                "target": mpath,
                "pid": None,
                "description": f"Known backdoor artifact present on disk: {mpath}"
            })

    for gpath in glob.glob("/var/tmp/.gsusr-*") + glob.glob("/tmp/.b044*"):
        threats.append({
            "id": f"file_{gpath}",
            "category": "Hidden Backdoor Directory",
            "severity": "HIGH",
            "target": gpath,
            "pid": None,
            "description": f"Suspicious hidden backdoor staging path: {gpath}"
        })

    # 4. Check rogue UID=0 users in /etc/passwd
    try:
        with open("/etc/passwd", "r", encoding="utf-8", errors="ignore") as f:
            for line in f:
                parts = line.strip().split(":")
                if len(parts) >= 4 and parts[2] == "0" and parts[0] != "root":
                    threats.append({
                        "id": f"user_{parts[0]}",
                        "category": "Rogue Root Account (UID 0)",
                        "severity": "CRITICAL",
                        "target": parts[0],
                        "pid": None,
                        "description": f"Unauthorized root-equivalent account '{parts[0]}' (UID=0) in /etc/passwd"
                    })
    except Exception:
        pass

    # 5. Check /etc/cron.d for hidden dot files or suspicious base64/curl commands
    for cfile in glob.glob("/etc/cron.d/*") + glob.glob("/etc/cron.d/.*"):
        bname = os.path.basename(cfile)
        if bname in (".", "..", ".placeholder", "cyberpanel-security-guard"):
            continue
        if bname.startswith("."):
            threats.append({
                "id": f"cron_{cfile}",
                "category": "Hidden Cron Persistence",
                "severity": "CRITICAL",
                "target": cfile,
                "pid": None,
                "description": f"Hidden dot-file in /etc/cron.d: {cfile}"
            })
            continue
        try:
            with open(cfile, "r", encoding="utf-8", errors="ignore") as f:
                content = f.read()
            if "base64 -d" in content or "trycloudflare.com" in content or "chmod 475" in content or "/tmp/." in content:
                threats.append({
                    "id": f"cron_payload_{cfile}",
                    "category": "Malicious Cron Payload",
                    "severity": "CRITICAL",
                    "target": cfile,
                    "pid": None,
                    "description": f"Suspicious command injection found in {cfile}"
                })
        except Exception:
            pass

    # 6. Check SUID binaries in /tmp, /var/tmp, /dev/shm
    suid_out = run_cmd("find /tmp /var/tmp /dev/shm -perm /6000 -type f 2>/dev/null")
    for sfile in suid_out.splitlines():
        sfile = sfile.strip()
        if sfile:
            threats.append({
                "id": f"suid_{sfile}",
                "category": "Privilege Escalation (SUID)",
                "severity": "CRITICAL",
                "target": sfile,
                "pid": None,
                "description": f"Unauthorized SUID/SGID binary in temp directory: {sfile}"
            })

    # 7. Check immutable files in /etc/udev/rules.d or /lib/systemd/system-generators
    lsattr_out = run_cmd("lsattr /etc/udev/rules.d/* /lib/systemd/system-generators/* 2>/dev/null")
    for line in lsattr_out.splitlines():
        parts = line.split()
        if len(parts) == 2 and "i" in parts[0]:
            threats.append({
                "id": f"immutable_{parts[1]}",
                "category": "Immutable Persistence Hook",
                "severity": "HIGH",
                "target": parts[1],
                "pid": None,
                "description": f"System file locked with immutable attribute (chattr +i): {parts[1]}"
            })

    result = {
        "scan_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "threat_count": len(threats),
        "status": "CLEAN" if len(threats) == 0 else "THREATS_DETECTED",
        "threats": threats
    }
    ensure_data_dir()
    try:
        with open(LAST_SCAN_FILE, "w", encoding="utf-8") as f:
            json.dump(result, f, indent=2)
    except Exception:
        pass
    return result


def remediate_threats(scan_result=None):
    if scan_result is None:
        scan_result = scan_server()

    actions = []
    threats = scan_result.get("threats", [])
    if not threats:
        return {"remediated_count": 0, "actions": ["No active threats found. System is clean."]}

    for t in threats:
        cat = t.get("category", "")
        target = t.get("target", "")
        pid = t.get("pid")

        if cat == "Hidden Process (/proc mount)" and target:
            run_cmd(f"umount -l {target} 2>/dev/null")
            if pid:
                try:
                    os.kill(int(pid), signal.SIGKILL)
                except Exception:
                    pass
            msg = f"Unmounted hidden /proc bind-mount {target} and killed PID {pid}"
            actions.append(msg)
            append_event("REMEDIATION", "CRITICAL", "Unmasked & Killed Hidden Process", t.get("description", ""), msg)

        elif cat == "Malicious Process":
            if target and os.path.exists(target) and not target.startswith(SAFE_SYSTEM_BINARIES):
                run_cmd(f"chattr -ia '{target}' 2>/dev/null")
                try:
                    os.remove(target)
                except Exception:
                    pass
            if pid:
                try:
                    os.kill(int(pid), signal.SIGKILL)
                except Exception:
                    pass
            msg = f"Terminated malicious PID {pid} and removed binary {target}"
            actions.append(msg)
            append_event("REMEDIATION", "CRITICAL", "Killed Malicious Process", t.get("description", ""), msg)

        elif cat in ("Backdoor File / Service", "Hidden Backdoor Directory", "Hidden Cron Persistence",
                     "Privilege Escalation (SUID)", "Immutable Persistence Hook"):
            if target and os.path.exists(target):
                run_cmd(f"chattr -ia -R '{target}' 2>/dev/null")
                try:
                    if os.path.isdir(target):
                        shutil.rmtree(target, ignore_errors=True)
                    else:
                        os.remove(target)
                except Exception:
                    pass
                msg = f"Unlocked (chattr -i) and deleted {target}"
                actions.append(msg)
                append_event("REMEDIATION", "HIGH", f"Removed {cat}", t.get("description", ""), msg)

        elif cat == "Malicious Cron Payload" and target and os.path.exists(target):
            run_cmd(f"chattr -ia '{target}' 2>/dev/null")
            run_cmd(f"sed -i '/base64 -d/d; /trycloudflare/d; /chmod 475/d; /\\/tmp\\/\\./d' '{target}' 2>/dev/null")
            msg = f"Sanitized injected lines from cron file {target}"
            actions.append(msg)
            append_event("REMEDIATION", "CRITICAL", "Sanitized Cron File", t.get("description", ""), msg)

        elif cat == "Rogue Root Account (UID 0)" and target and target != "root":
            run_cmd("chattr -ia /etc/passwd /etc/shadow /etc/group /etc/gshadow 2>/dev/null")
            run_cmd(f"sed -i '/^{target}:/d' /etc/passwd /etc/shadow /etc/group /etc/gshadow 2>/dev/null")
            msg = f"Removed unauthorized UID=0 root user '{target}' from /etc/passwd and /etc/shadow"
            actions.append(msg)
            append_event("REMEDIATION", "CRITICAL", "Removed Rogue Root Account", t.get("description", ""), msg)

    run_cmd("udevadm control --reload-rules 2>/dev/null; systemctl daemon-reload 2>/dev/null")
    # Re-scan to update last_scan.json
    scan_server()
    return {"remediated_count": len(actions), "actions": actions}


def enforce_cpu_guard():
    cfg = load_config()
    if not cfg.get("cpu_guard_enabled", True):
        return {"status": "disabled", "actions": []}

    metrics = get_system_metrics()
    actions = []
    max_thresh = float(cfg.get("max_cpu_threshold", 85.0))
    proc_limit = float(cfg.get("per_process_cpu_limit", 75.0))
    max_lsphp = int(cfg.get("max_lsphp_per_user", 12))

    # 1. Check per-user lsphp process count to prevent PHP flood / DoS saturating CPU
    out = run_cmd("ps -eo pid,user,pcpu,etimes,comm | grep lsphp")
    user_lsphp = {}
    for line in out.splitlines():
        parts = line.split()
        if len(parts) >= 5 and "lsphp" in parts[4]:
            try:
                pid = int(parts[0])
                user = parts[1]
                pcpu = float(parts[2])
                age = int(parts[3])
                user_lsphp.setdefault(user, []).append((pcpu, age, pid))
            except Exception:
                pass

    for user, plist in user_lsphp.items():
        if len(plist) > max_lsphp:
            # Sort by highest CPU/age and terminate excess workers beyond limit
            plist.sort(reverse=True)
            to_kill = plist[max_lsphp:]
            for pcpu, age, pid in to_kill:
                try:
                    os.kill(pid, signal.SIGKILL)
                except Exception:
                    pass
            msg = f"Throttled excess lsphp workers for user '{user}' ({len(plist)} active > limit {max_lsphp}, killed {len(to_kill)} workers)"
            actions.append(msg)
            append_event("CPU_GUARD", "WARNING", "PHP Worker Flood Prevented",
                         f"User {user} spawned {len(plist)} concurrent lsphp processes.", msg)

    # 2. Check high CPU processes and renice or throttle them
    for proc in metrics.get("top_processes", []):
        pid = proc["pid"]
        pcpu = proc["cpu"]
        comm = proc["comm"]
        user = proc["user"]

        if pcpu >= proc_limit:
            # If it's a legitimate service (mariadbd, java/elasticsearch, lsphp, litespeed), renice to +15 and ionice
            if any(k in comm for k in ("lsphp", "java", "mariadbd", "mysqld", "python", "litespeed", "gzip", "tar")):
                current_nice = 0
                try:
                    current_nice = int(proc["nice"])
                except Exception:
                    pass
                if current_nice < 15:
                    run_cmd(f"renice -n 19 -p {pid} >/dev/null 2>&1; ionice -c 3 -p {pid} >/dev/null 2>&1")
                    msg = f"Deprioritized high-CPU process PID {pid} ({comm}, {pcpu}% CPU) to nice +19 / idle I/O"
                    actions.append(msg)
                    append_event("CPU_GUARD", "INFO", "High CPU Process Throttled",
                                 f"Process {comm} (PID {pid}, user {user}) was consuming {pcpu}% CPU.", msg)
            elif cfg.get("kill_unknown_high_cpu", True) and metrics["cpu_percent"] >= max_thresh:
                # Check if binary is outside safe paths
                try:
                    exe = os.readlink(f"/proc/{pid}/exe")
                except Exception:
                    exe = ""
                if exe and not exe.startswith(SAFE_SYSTEM_BINARIES):
                    try:
                        os.kill(pid, signal.SIGKILL)
                        msg = f"Killed unknown runaway process PID {pid} ({exe}, {pcpu}% CPU) to prevent 100% CPU lockup"
                        actions.append(msg)
                        append_event("CPU_GUARD", "CRITICAL", "Runaway Unknown Process Terminated",
                                     f"Unknown binary {exe} consumed {pcpu}% CPU while total CPU was {metrics['cpu_percent']}%.", msg)
                    except Exception:
                        pass

    return {"status": "enforced", "metrics": metrics, "actions": actions}


def run_routine_cron():
    cfg = load_config()
    scan_res = scan_server()
    if scan_res.get("threat_count", 0) > 0 and cfg.get("auto_remediate", True):
        remediate_threats(scan_res)
    if cfg.get("cpu_guard_enabled", True):
        enforce_cpu_guard()


def get_dashboard_status():
    cfg = load_config()
    metrics = get_system_metrics()
    if os.path.exists(LAST_SCAN_FILE):
        try:
            with open(LAST_SCAN_FILE, "r", encoding="utf-8") as f:
                last_scan = json.load(f)
        except Exception:
            last_scan = scan_server()
    else:
        last_scan = scan_server()

    f2b_active = run_cmd("systemctl is-active fail2ban") == "active"
    cron_active = os.path.exists(CRON_FILE)

    return {
        "status": 1,
        "config": cfg,
        "metrics": metrics,
        "last_scan": last_scan,
        "events": get_events()[:40],
        "fail2ban_active": f2b_active,
        "cron_active": cron_active
    }


if __name__ == "__main__":
    if "--cron" in sys.argv:
        run_routine_cron()
    elif "--scan" in sys.argv:
        print(json.dumps(scan_server(), indent=2))
    elif "--remediate" in sys.argv:
        print(json.dumps(remediate_threats(), indent=2))
    elif "--cpuguard" in sys.argv:
        print(json.dumps(enforce_cpu_guard(), indent=2))
    elif "--init" in sys.argv:
        cfg = save_config(DEFAULT_CONFIG)
        run_routine_cron()
        print("Initialized Security Shield & CPU Guard successfully.")

    elif "--api-json" in sys.argv:
        idx = sys.argv.index("--api-json")
        payload = json.loads(sys.argv[idx + 1]) if idx + 1 < len(sys.argv) else {}
        action = payload.get("action", "status")
        if action == "status":
            print(json.dumps(get_dashboard_status()))
        elif action == "scan":
            print(json.dumps({"status": 1, "scan": scan_server()}))
        elif action == "remediate":
            print(json.dumps({"status": 1, "result": remediate_threats()}))
        elif action == "cpuguard":
            print(json.dumps({"status": 1, "result": enforce_cpu_guard()}))
        elif action == "save_config":
            print(json.dumps({"status": 1, "config": save_config(payload.get("config", {}))}))
        elif action == "proc_action":
            pid = int(payload.get("pid", 0))
            sub = payload.get("sub_action", "")
            if pid <= 1:
                print(json.dumps({"status": 0, "message": "Gecersiz PID"}))
            elif sub == "renice":
                run_cmd(f"renice -n 19 -p {pid} >/dev/null 2>&1; ionice -c 3 -p {pid} >/dev/null 2>&1")
                append_event("MANUAL", "INFO", f"PID {pid} Yavaslatildi", f"Kullanici mudahalesi ile PID {pid} nice +19 yapildi.", "Renice +19")
                print(json.dumps({"status": 1, "message": f"PID {pid} dusuk oncelige (Nice +19) cekildi."}))
            elif sub == "kill":
                os.kill(pid, signal.SIGKILL)
                append_event("MANUAL", "WARNING", f"PID {pid} Sonlandirildi", f"Kullanici mudahalesi ile PID {pid} olduruldu.", "SIGKILL")
                print(json.dumps({"status": 1, "message": f"PID {pid} basariyla sonlandirildi."}))

    else:
        print(json.dumps(get_dashboard_status(), indent=2))
