import subprocess
import sys

service_name = sys.argv[1]
operation = sys.argv[2]


try:
    check_proc = subprocess.Popen(['systemctl', 'status', f'{service_name}.service'],
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE,
                               universal_newlines=True)

    stdout_data, stderr_data = check_proc.communicate()
except FileNotFoundError:
    print('systemd is not installed')
    sys.exit(0)

if stderr_data.find('could not be found') != -1:
    print(f'{service_name} not installed')
    sys.exit(0)


proc = subprocess.Popen(['systemctl', operation, f'{service_name}.service'],
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE,
                            universal_newlines=True,bufsize=1000)

stdout_data, stderr_data = proc.communicate()

if operation == 'status':
    is_success = proc.returncode in [0, 3]
else:
    is_success = proc.returncode == 0

if is_success:
    print(f'{service_name} {operation} successfully')
    if operation == 'status':
        print(stdout_data)
    sys.exit(0)
else:
    print(f'{service_name} {operation} error (code {proc.returncode})')
    print(stderr_data)
    sys.exit(proc.returncode)