#!/opt/catchpoint/bin/python
import json, subprocess, sys

def is_alpine():
    with open("/etc/os-release") as f:
        for line in f:
            if line.startswith("ID="):
                key,value = line.rstrip().split("=")
                return value == "alpine"
        return False

def is_systemd():
    try:
        proc = subprocess.Popen(['ps', '-p', '1', '-o', 'comm='], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out, err = proc.communicate()
        # Decode the output from bytes to string
        output = out.decode('utf-8').strip()
        # Check if the output contains "systemd"
        if "systemd" in output:
            return True
        else:
            return False
    except Exception as e:
        print(str(e))
        return (False, str(e))

def service_ctl(data):
    rc = False
    msg = "success"
    try:
        action = data[0]
        service_name = data[1]

        # Whitelisted actions
        ["restart","start","status","stop","is-active"].index(action) # throws ValueError
        # Whitelisted services
        ["commeng", "cpinit", "cpsecurestore", "cpsns", "pacprocessor", "testeng", "txeng", "xvfb"].index(service_name)

        if is_systemd() == True:
            proc = subprocess.Popen(['/usr/bin/systemctl', action, service_name], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        elif is_alpine() == True:
            real_action = action
            if action == "is-active":
                real_action = "status"
            proc = subprocess.Popen(['/sbin/rc-service', service_name, real_action], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        else:
            # Fall back to supervisorctl.
            real_action = action
            if action == "is-active":
                real_action = "status"
            proc = subprocess.Popen(['/usr/local/bin/supervisorctl', real_action, service_name], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

        out, err = proc.communicate()
        ret = proc.returncode
        if ret == 0:
            rc = True
            msg = out.decode('utf8')
        else:
            msg = "Failed to " + action + " " + service_name + ": " + err
    except Exception as e:
        return (False, str(e))

    return (rc, msg)

data = sys.stdin.read()
data = json.loads(data)

print(json.dumps(service_ctl(data)))
