#
# Copyright (C) 2019-Present A-Team Digital Solutions
#
"""
Script Runner

Runs shell scripts using the current
Project environment.
"""

import os
import subprocess
import threading
from pathlib import Path

#
# ROM-Builder root directory
#
ROOT = Path(
    __file__
).resolve().parent.parent
def run_script(project, script):
    #
    # Build environment
    #
    env = os.environ.copy()
    env.update(
        project.as_environment()
    )
    #
    # Resolve script path
    #
    script_path = ROOT / script
    #
    # Verify script exists
    #
    if not script_path.is_file():
        print(
            f"Script Not Found: {script_path}"
        )
        return False
    #
    # Run from ROM-Builder root
    #
    cwd = str(ROOT)
    print()
    print("========== RUNNING ==========")
    print(f"Script   : {script_path}")
    print(f"CWD      : {cwd}")
    print(f"ROM_PATH : {project.rom_path}")
    print("=============================")
    print()
    result = subprocess.run(
        [
            "bash",
            str(script_path)
        ],
        cwd=cwd,
        env=env
    )
    return (
        result.returncode == 0
    )
def run_script_async(
    project,
    script
):
    threading.Thread(
        target=run_script,
        args=(project, script),
        daemon=True
    ).start()
