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

import os
import tempfile
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
SCRIPTS = ROOT / "scripts"

def _shell_quote(value):
    """
    Safely quote a value for shell usage.
    """
    value = str(value)
    return "'" + value.replace(
        "'",
        "'\"'\"'"
    ) + "'"
def _make_command(project, script):
    """
    Generate a shell command that loads the Project
    environment from a temporary file before executing
    the requested script.
    """
    env = project.as_environment()
    #
    # Create temporary environment file.
    #
    fd, env_file = tempfile.mkstemp(
        prefix="a-team-env-",
        suffix=".sh"
    )
    try:
        with os.fdopen(
            fd,
            "w",
            encoding="utf-8"
        ) as f:
            for key, value in env.items():
                f.write(
                    f"export {key}="
                    f"{_shell_quote(value)}\n"
                )
    except Exception:
        Path(env_file).unlink(
            missing_ok=True
        )
        raise
    #
    # Load environment file, run script,
    # preserve exit status, then remove file.
    #
    return (
        f"source {_shell_quote(env_file)}"
        f" && bash {_shell_quote(script)}"
        f"; status=$?"
        f"; rm -f {_shell_quote(env_file)}"
        f"; echo"
        f"; echo \"A-Team Script Exit Code: $status\""
    )
#
# BUILD
#
def build_command(
    project,
    android_version,
    build_jobs,
    use_ccache
):
    project.android_version = android_version
    project.build_jobs = build_jobs
    project.use_ccache = use_ccache
    return _make_command(
        project,
        SCRIPTS / "build.sh"
    )
#
# SYNC
#
def sync_command(project):
    return _make_command(
        project,
        SCRIPTS / "sync.sh"
    )
#
# MINDTHEGAPPS SYNC
#
def gapps_sync_command(project):
    return _make_command(
        project,
        SCRIPTS / "gapps_sync.sh"
    )
#
# CLEAN
#
def clean_command(project):
    return _make_command(
        project,
        SCRIPTS / "clean.sh"
    )
