#!/usr/bin/env python3

import argparse
import os
import subprocess
import sys

OK=0
WARN=1
FAIL=2

def get_status_cmd(daemon):
    testpath = '/usr/sbin/service'
    if os.path.isfile(testpath) and os.access(testpath, os.X_OK):
        return [testpath, daemon, 'status']
    testpath = '/sbin/rc-service'
    if os.path.isfile(testpath) and os.access(testpath, os.X_OK):
        return [testpath, daemon, 'status']
    print('No service command found')
    sys.exit(FAIL)

def main():
    parser = argparse.ArgumentParser(description='Check if a service is running')
    parser.add_argument('daemon', nargs=1, help='Service name to test')
    args = parser.parse_args()

    daemon = args.daemon[0]
    cmd = get_status_cmd(daemon)
    proc = subprocess.Popen(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE)
    (out, err) = proc.communicate()

    if proc.returncode == OK and not err:
        print(out.decode('utf8'))
        return OK
    print("'{}' returned {}".format(' '.join(cmd), proc.returncode))
    print("\nstdout: {}\nstderr: {}".format(out.decode('utf8'), err.decode('utf8')))
    return FAIL


if __name__ == '__main__':
    sys.exit(main())
