import subprocess
import sys

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

try:
    check_proc = subprocess.Popen(['docker', 'ps', '-a', '-f', f'name={container_name}', '--format', '{{.Names}}'],
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE,
                               universal_newlines=True)

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

matched_containers = stdout_data.strip().split('\n')
if container_name not in matched_containers:
    print(f'{container_name} container not installed')
    sys.exit(0)

proc = subprocess.Popen(['docker', operation, f'{container_name}'],
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE,
                                universal_newlines=True)
proc.wait()

if proc.returncode != 0:
    print(f'Docker command failed')
    sys.exit(check_proc.returncode)

if proc.returncode == 0:
    print(f'{container_name} {operation} successfully')
else:
    print(f'{container_name} {operation} error')

sys.exit(proc.returncode)