#!/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 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
        ["cpsns"].index(service_name)
        if is_alpine() == False:
            proc = subprocess.Popen(['/usr/bin/systemctl', action, service_name], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        else:
            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)
        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)))
