#!/usr/bin/env python3
import os
import time
import shutil
import subprocess
import sys

sys.path.append('/opt/opengnsys/lib/engine/bin')
import ogGlobals
import SystemLib

def main(arg1, arg2, dest_file):
    start_time = time.time()

    og_log_session = os.getenv(ogGlobals.OGLOGSESSION)
    og_log_command = os.getenv(ogGlobals.OGLOGCOMMAND)
    if og_log_session and og_log_command:
        with open(og_log_session, 'w') as f:
            f.write(" ")
        with open(og_log_command, 'w') as f:
            f.write(" ")
        with open(f"{og_log_command}.tmp", 'w') as f:
            f.write(" ")

    msg_interface_start = os.getenv(ogGlobals.lang.MSG_INTERFACE_START)
    if msg_interface_start:
        SystemLib.ogEcho("log", "session", f"{msg_interface_start} {__file__} {arg1} {arg2}")

    try:
        result = subprocess.run(
            ["python3", "/opt/opengnsys/scripts/listSoftwareInfo.py", arg1, arg2],
            capture_output=True,
            text=True,
            check=True
        )
        file = result.stdout.strip().splitlines()[-1]
    except subprocess.CalledProcessError as e:
        print(f"Error al ejecutar listSoftwareInfo: {e.stderr}")
        sys.exit(e.returncode)

    print(f"Copying:( {file} to {dest_file} )")
    shutil.copy(file, dest_file)

    elapsed_time = time.time() - start_time
    msg_scripts_time_partial = os.getenv(ogGlobals.lang.MSG_SCRIPTS_TIME_PARTIAL)
    if msg_scripts_time_partial:
        SystemLib.ogEcho("log", "session", f"   [ ]      {msg_scripts_time_partial} : {int(elapsed_time // 60)}m {int(elapsed_time % 60)}s")

if __name__ == "__main__":
    if len(sys.argv) != 4:
        print("Usage: python InventarioSoftware.py <arg1> <arg2> <dest_file>")
        sys.exit(1)
    main(sys.argv[1], sys.argv[2], sys.argv[3])
