#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-

import sys
import os
import subprocess

def main():
    if len(sys.argv) < 3:
        print("Error: Missing parameters.")
        print("Usage: {} <action> <service>".format(sys.argv[0]))
        sys.exit(1)

    action = sys.argv[1]
    service = sys.argv[2]

    init_services = [
        "zabbix-proxy", "zabbix-agent", "docker", "ntopng", "suricata",
        "unifi", "fail2ban", "syslog-ng", "kula", "emailrelay",
        "vmtoolsd", "ddns-clients", "tailscaled", "qemu-ga"
    ]

    # --- GROUP 1: SYSTEM (Via /init.d) ---
    if service in init_services:
        cmd = "nohup /etc/init.d/{} {} > /dev/null 2>&1 &".format(service, action)
        os.system(cmd)

    elif service == "nxfilter":
        if action == "restart":
            cmd = "nohup /usr/local/bin/nxfilter --restart > /dev/null 2>&1 &"
            os.system(cmd)
        else:
            print("Action '{}' not allowed for NXFilter (Only 'restart' is supported).".format(action))
            sys.exit(1)

    elif service == "wireguard":
        if action == "restart":
            subprocess.call(["/usr/local/bin/wireguard", "--server"])
        else:
            print("Action '{}' not allowed for WireGuard Server (Only 'restart' is supported).".format(action))
            sys.exit(1)

    elif service.startswith("wireguard-"):
        iface = service.replace("wireguard-", "", 1)
        if action == "restart":
            subprocess.call(["/usr/local/bin/wireguard", "--restart", "--interface={}".format(iface)])
        else:
            print("Action '{}' not allowed for WireGuard interface '{}' (Only 'restart' is supported).".format(iface, action))
            sys.exit(1)

    # --- GROUP 2: SYSTEM (Via /sbin/jobcontrol) ---
    else:
        job_map = {
            "sshd": "ssh",
            "ntpd": "ntp",
            "dhcp-server": "dhcp",
            "openvpn": "openvpnjob",
            "dnsmasq": "dnsmasq",
            "fcron": "fcron",
            "emi": "emi",
            "httpd": "httpd",
            "jobsengine": "jobsengine",
            "samba": "samba",
            "winbind": "winbind",
            "squid": "squid",
            "ipsec": "ipsec",
            "clamd": "clamav"
        }

        job_name = job_map.get(service, service)
        subprocess.call(["/sbin/jobcontrol", action, job_name])

if __name__ == "__main__":
    main()