import os
import subprocess

print("==============================================")
print("OpenGnsys Clonning Engine Start...")
# Cargar entorno de OpenGnsys
os.environ['OGETC'] = '/opt/opengnsys/etc'
print (f"OGETC: {os.environ['OGETC']}")

os.environ['PYTHONUNBUFFERED'] = '1'

loadenviron_path = os.path.join(os.environ['OGETC'], 'preinit', 'loadenviron.sh')

print (f"loadenviron_path: {loadenviron_path}")
subprocess.run(['bash', '-c', f'set -a && source {loadenviron_path} && set +a'], shell=True)
print("==============================================")

# Scripts de inicio

scripts = ['fileslinks', 'loadmodules', 'metadevs', 'mountrepo', 'poweroff', 'otherservices']
for script in scripts:
    script_path = os.path.join(os.environ['OGETC'], 'preinit', f'{script}.sh')
    print (f"script_path: {script_path}")
    subprocess.run(['bash', script_path])

# Check and run the appropriate init script
init_scripts = [
    os.path.join(os.environ['OGETC'], 'init', f'{os.environ.get("IPV4ADDR", "")}.sh'),
    os.path.join(os.environ['OGETC'], 'init', f'{os.environ.get("OGGROUP", "")}.sh'),
    os.path.join(os.environ['OGETC'], 'init', 'default.sh')
]

for script in init_scripts:
    if os.path.isfile(script):
        subprocess.run(['bash', script])
        break
else:
    print("No se ha encontrado script de inicio")
    subprocess.run(['halt'])

print("OpenGnsys Clonning Engine End.")
print("==============================================")
