#!/usr/bin/python3

import os
import time
import subprocess
import sys

import ogGlobals
from SystemLib import ogEcho, ogRaiseError


prog = sys.argv[0]
if len (sys.argv) != 2:
    print (f'Usage: {prog} <script_path>')
    sys.exit (1)

TIME1 = time.time()
script_path = sys.argv[1]

# Clear temporary file used as log track by httpdlog
# Limpia los ficheros temporales usados como log de seguimiento para httpdlog
open (ogGlobals.OGLOGSESSION, 'w').close()
open (ogGlobals.OGLOGCOMMAND, 'w').close()

# Registro de inicio de ejecución
ogEcho (['log', 'session'], None, f'{ogGlobals.lang.MSG_INTERFACE_START} {prog} {script_path}')

with open (ogGlobals.OGLOGFILE, 'a') as logfd:
    with open (script_path) as scriptfd:
        logfd.write ('\n Instrucciones a ejecutar: *****************************\n')
        logfd.write (scriptfd.read())

    logfd.write ('\n Salida de las instrucciones: *****************************\n')

os.chmod (script_path, 0o755)
# Si mandamos la salida a OGLOGCOMMAND reescribimos lo que manda el comando.
RETVAL = subprocess.run (['bash', script_path]).returncode


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

# Registro de fin de ejecución
ogEcho (['log', 'session'], None, f'{ogGlobals.lang.MSG_INTERFACE_END} {RETVAL}')

sys.exit (RETVAL)
