
import os, sys
import subprocess
import argparse

format_string = "{:25} {:4} {:5} {:7} {:7}"

parser = argparse.ArgumentParser()
parser.add_argument('-r', '--remote', help='Name of a remote computer')
args = parser.parse_args()

# parser.print_help()
# print("")
# print("")

if not sys.platform.startswith('win'):
    raise RuntimeError("This function is to be used in windows only")


def get_uptime(computer_name):
    cmd = "systeminfo /s {}".format(computer_name)

    p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    (child_stdin, child_stdout) = (p.stdin, p.stdout)
    lines = child_stdout.readlines()
    child_stdin.close()
    child_stdout.close()

    lines = [line.strip() for line in lines if line.strip()]
    m = 0; d = 0; y = 0; H = 0; M = 0; S = 0

    for line in lines:
        if 'System Boot Time:' in str(line):
            line = str(line)
            date, time, ampm = line.split()[3:6]
            date = date.replace(',', '')

            m, d, y = [int(v) for v in date.split('/')]
            H, M, S = [int(v) for v in time.split(':')]
            if 'pm' in ampm.lower() and H < 12:
                H += 12

            break

    if m + d + y + H + M + S > 0:
        import datetime

        now = datetime.datetime.utcnow()
        then = datetime.datetime(y, m, d, H, M)

        diff = now - then
        s = ""
        hours = int(diff.seconds / 60 / 60)
        minutes = int(diff.seconds / 60 % 60)
        seconds = int(diff.seconds % 60)

        print(format_string.format(computer_name, diff.days, hours, minutes, seconds))
    else:
        print("Couldn't find a start date")

    return s


file_with_list_of_computers_to_check = sys.argv[0].replace('.py', '.txt')
if not os.path.exists(file_with_list_of_computers_to_check):
    with open(file_with_list_of_computers_to_check, "w") as input_file:
        if args.remote == None:
            input_file.write("localhost\n")
        else:
            input_file.write("{}\n".format(args.remote))

print(format_string.format("Computer Uptime", "Days", "Hours", "Minutes", "Seconds"))
need_to_save_argument = (args.remote != None)
with open(file_with_list_of_computers_to_check, "r") as input_file:
    for line in input_file:
        computer = line.strip().lower()
        if args.remote != None and args.remote.lower() == computer:
            need_to_save_argument = False
        get_uptime(computer)

if need_to_save_argument:
    get_uptime(args.remote)
    with open(file_with_list_of_computers_to_check, "a") as input_file:
        input_file.write(args.remote + "\n")

print("\nDatabase file is {}\n".format(file_with_list_of_computers_to_check))

