#!/usr/bin/python3
import sys, ast, platform
import subprocess
from time import sleep
from datetime import datetime


def get_time():
    ts1 = str(datetime.now()).split('.')[0]
    return ts1


def call_shutdown(client_type, clientid):
    if client_type == 'vm':
        subprocess.run(['/usr/sbin/qm', 'shutdown', clientid])
    elif client_type == 'lxc':
        subprocess.run(['/usr/bin/lxc-stop', clientid])
    else:
        print('Unable to stop {clientid}. Invalid client type or client id')
        print(f'client_type: {client_type}')
        print(f'client id: {clientid}')


def get_status(client_type, clientid, vmstatus, status_wanted):
    checker = None
    if client_type == 'lxc':
        checker = subprocess.check_output(['lxc-info', clientid])
    elif client_type == 'vm':
        checker = subprocess.check_output(['/usr/sbin/qm', 'status', clientid])
    while vmstatus != status_wanted:
        sleep(5)
        vmoutput = checker
        if (str.encode(status_wanted)) in vmoutput.upper():
            vmstatus = status_wanted
    return status_wanted


def print_state(vmtype, vmhost, vmstatus):
    print(f'{vmtype} {vmhost} is {vmstatus}')


def client_shutdown(client_type, clientid):
    failed_attempt = 0
    vresult = None
    try:
        print(f'Stopping {clientid}')
        call_shutdown(client_type, clientid)
        vresult = get_status(client_type, clientid, 'RUNNING', 'STOPPED')
    except Exception as e:
        print(f'Unable to stop container {clientid}: {e}')
        failed_attempt = 1
    return ([failed_attempt, client_type, clientid])


def main():
    client_type = None
    client_list = None
    failed_count = 0
    fail_list = []
    try:
        client_type = sys.argv[1]
        client_list = ast.literal_eval(sys.argv[2])
    except Exception as e:
        print(f'Unable to process cli arguments. {e}')
    else:
        print(f'{client_type} {client_list}')
    timestamp = get_time()
    print(f'Start time: {timestamp}')
    for clientid in client_list:
        counter = client_shutdown(client_type, clientid)
        failed_count += counter[0]
        fail_list.append(counter[1:])
    print(f'Successfully stopped client list.')

    timestamp = get_time()
    print(f'End time: {timestamp}')


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