#!/usr/bin/python3
"""In-container entrypoint for automotive-image-builder.

Run as the container command by the host-side aib.sh / aib-dev.sh wrapper. It
performs the in-container setup that is required for the container to work.

Setup performed:
  * osbuild must run with the SELinux install_exec_t type. The osbuild binary
    lives on a read-only image layer and cannot be relabeled in place, so we
    copy it onto a fresh tmpfs, relabel the copy, and put that first on PATH.
  * The --src option can be passed, allowing the script to use a development
    snapshot of the aib code from the host.

"""

import os
import shutil
import subprocess
import sys

AIB_TMPFS = "/run/aib"


def setup_osbuild():
    osbuild = shutil.which("osbuild")
    if osbuild is None:
        # Nothing to relabel; let aib fail later with a clearer message.
        return

    os.makedirs(AIB_TMPFS, exist_ok=True)
    # A private tmpfs we can relabel on (image layers are read-only).
    if not os.path.ismount(AIB_TMPFS):
        subprocess.run(["mount", "-t", "tmpfs", "none", AIB_TMPFS], check=True)

    dest = os.path.join(AIB_TMPFS, "osbuild")
    shutil.copyfile(osbuild, dest)
    os.chmod(dest, 0o755)
    subprocess.run(
        ["chcon", "system_u:object_r:install_exec_t:s0", dest], check=True
    )

    os.environ["PATH"] = AIB_TMPFS + os.pathsep + os.environ.get("PATH", "")


def main():
    argv = sys.argv[1:]

    src_dir = None
    if len(argv) >= 2 and argv[0] == "--src":
        src_dir = argv[1]
        argv = argv[2:]

    prog = "aib-dev" if "dev" in os.path.basename(sys.argv[0]) else "aib"

    setup_osbuild()

    if src_dir:
        target = os.path.join(src_dir, "bin", prog)
    else:
        target = shutil.which(prog) or os.path.join("/usr/bin", prog)

    os.execv(target, [target] + argv)


if __name__ == "__main__":
    sys.exit(main())
