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

def load_engine_config():
    engine_config_path = "/opt/opengnsys/etc/engine.cfg"
    if os.path.exists(engine_config_path):
        with open(engine_config_path) as f:
            exec(f.read(), globals())

def clear_temp_logs():
    open(os.getenv('OGLOGSESSION'), 'w').close()
    open(os.getenv('OGLOGCOMMAND'), 'w').close()
    open(f"{os.getenv('OGLOGCOMMAND')}.tmp", 'w').close()

def log_session_start(script_name, args):
    SystemLib.ogEcho("log session", f"{os.getenv('MSG_INTERFACE_START')} {script_name} {' '.join(args)}")

def log_session_end(retval):
    SystemLib.ogEcho("log session", f"{os.getenv('MSG_INTERFACE_END')} {retval}")

def ogCheckIpAddress(ip):
    try:
        subprocess.check_call(["ping", "-c", "1", ip])
        return 0
    except subprocess.CalledProcessError:
        return 1

def create_image(disk_num, partition_num, repo, image_name):
    if subprocess.call(["which", "createImageCustom"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) == 0:
        return subprocess.call(["createImageCustom", disk_num, partition_num, repo, f"/{image_name}"])
    else:
        return subprocess.call(["createImage", disk_num, partition_num, repo, f"/{image_name}"])

def main():
    if len(sys.argv) != 5:
        sys.exit(SystemLib.ogRaiseError(OG_ERR_FORMAT, "Incorrect number of arguments"))

    disk_num, partition_num, image_name, repo = sys.argv[1:5]

    start_time = time.time()

    load_engine_config()
    clear_temp_logs()
    log_session_start(sys.argv[0], sys.argv[1:])

    repo = repo if repo else "REPO"
    if repo == NetLib.ogGetIpAddress():
        repo = "CACHE"

    if ogCheckIpAddress(repo) == 0 or repo == "REPO":
        OGUNIT = os.getenv('OGUNIT', "")
        if not NetLib.ogChangeRepo(repo, OGUNIT):
            sys.exit(SystemLib.ogRaiseError(OG_ERR_NOTFOUND, f"{repo}"))

    if repo == "REPO" and os.getenv('boot') != "admin":
        retval = CambiarAcceso("admin")
        if retval > 0:
            sys.exit(retval)

    retval = create_image(disk_num, partition_num, repo, image_name)

    if repo == "REPO" and os.getenv('boot') != "admin":
        CambiarAcceso("user")

    log_session_end(retval)
    sys.exit(retval)

if __name__ == "__main__":
    main()
