#
# 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 exports the Project environment
    and executes the requested script.

    The environment is embedded directly in the command instead of
    being written to a local temporary file.  This is required for
    SSH/remote build hosts because a local /tmp file does not exist
    on the remote machine.
    """
    env = project.as_environment()

    #
    # Build the exports inline so the complete command can be sent
    # through the terminal locally or over SSH.
    #
    exports = "\n".join(
        f"export {key}={_shell_quote(value)}"
        for key, value in env.items()
    )

    #
    # Run the script, preserve its exit status, then report it.
    #
    return (
        f"{exports}\n"
        f"bash {_shell_quote(script)}"
        f"; status=$?"
        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"
    )
