import datetime
import os
import shutil
import time


def getInfo(file_result):
    with open(r"D:\Visual Studio Code\GetBaseLine-old\command.txt", "r") as commands:
        datacmd = commands.read()
    commands_list = datacmd.splitlines()
    log_file = file_result
    with open(log_file, "a") as log:
        try:
            time.sleep(2)
            logtime = datetime.datetime.now()
            log.write(
                "\n\n---------------------------------------------------------------------------------------------------------------------------\n"
            )
            log.write(str(logtime))
            for command in commands_list:
                crt.Screen.Send(command + "\n")
                response = crt.Screen.ReadString(">")
                # log.write( response)
                log.write("> " + command + response)
                time.sleep(1)
            log.write("> " + command + response)
        except Exception as e:
            log.write("Error occurred: " + str(e))
            crt.Dialog.MessageBox("Error occurred: " + str(e))


def remove_empty_lines(file_path):
    with open(file_path, "r") as file:
        lines = file.readlines()
    with open(file_path, "w") as file:
        for line in lines:
            if line.strip():
                file.write(line)


def main():
    with open("D:\Visual Studio Code\GetBaseLine-old\ip_device.txt", "r") as commands:
        dataIP = commands.read()
    list_ip_device = dataIP.splitlines()
    file_result = "D:\Visual Studio Code\GetBaseLine-old\Result\HardwareHealthCheck.txt"
    for ip in list_ip_device:
        try:
            crt.Screen.Send("ssh %s\n" % ip)
            if not crt.Screen.WaitForString("assword:", 10):
                crt.Dialog.MessageBox("Failed to get password prompt for %s" % ip)
                continue
            crt.Screen.Send("Hau@vng310823\n")
            if not crt.Screen.WaitForString("{master:0}", 10):
                crt.Dialog.MessageBox("Failed to login to %s" % ip)
                continue
            time.sleep(2)
            getInfo(file_result)
            crt.Screen.Send("quit\n")
            if not crt.Screen.WaitForString("closed.", 5):
                crt.Dialog.MessageBox("Failed to logout from %s" % ip)
                continue
            time.sleep(0.5)
        except Exception as e:
            crt.Dialog.MessageBox("Error with device %s: %s" % (ip, str(e)))
    remove_empty_lines(file_result)
    crt.Dialog.MessageBox("Script completed. Check the log for details.")


main()
