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

#sys.path.append('/opt/opengnsys/lib/engine/bin')

def main(script_path):
    start_time = time.time()
    print(f"Ejecutando:",script_path)

    # Load engine configurator from engine.cfg file.
    engine_config_path = '/opt/opengnsys/etc/engine.cfg'
#    if 'OGENGINECONFIGURATE' not in os.environ:
#        with open(engine_config_path) as f:
#            exec(f.read(), globals())

    # Clear temporary file used as log track by httpdlog
    with open(os.environ['OGLOGSESSION'], 'w') as f:
        f.write("")
    with open(os.environ['OGLOGCOMMAND'], 'w') as f:
        f.write("")

    # Registro de inicio de ejecución
    SystemLib.ogEcho('log session', f"{os.environ['MSG_INTERFACE_START']} {sys.argv[0]} {' '.join(sys.argv[1:])}")

    with open(os.environ['OGLOGFILE'], 'a') as log_file:
        log_file.write("\n Instrucciones a ejecutar: *****************************\n"
        with open(script_path.split()[1]) as script_file:  # Obtener solo el nombre del script
            log_file.write(script_file.read())                       )

        log_file.write("\n Salida de las instrucciones: *****************************\n")

    # Cambiar permisos y ejecutar el script
    os.chmod(script_path.split()[1], 0o755)
    result = subprocess.run([sys.executable] + script_path.split(), capture_output=True, text=True)
    ret_val = result.returncode

    with open(os.environ['OGLOGCOMMAND'], 'a') as log_command_file:
        log_command_file.write(result.stdout)
        log_command_file.write(result.stderr)

    elapsed_time = time.time() - start_time
    if ret_val == 0:
        SystemLib.ogEcho('log session', f"[100] Duracion de la operacion {int(elapsed_time // 60)}m {int(elapsed_time % 60)}s")
    else:
        SystemLib.ogRaiseError('log session', ret_val)
        SystemLib.ogEcho('log session', 'error "Operacion no realizada"')

    # Registro de fin de ejecución
    SystemLib.ogEcho('log session', f"{os.environ['MSG_INTERFACE_END']} {ret_val}")

    sys.exit(ret_val)

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: python EjecutarScript.py <script_path>")
        sys.exit(1)
    main(sys.argv[1])
