#!/usr/bin/env python3
import argparse
import os
import sys
import subprocess

gitpath = os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), "../.git")
if os.path.exists(gitpath):
    # run from git repo
    sys.path.append(os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), ".."))

from fchroot.binfmt import *

exec_mode = False
verbose = False
NICK = "Emperor Schmoo"
VERSION = "0.3.0"


def bind_mount(chroot_path, umount=False):
    # auto-mount any necessary things automatically as a convenience
    mounts = ["proc", "sys", "dev"]
    for mount in mounts:
        action = "MOUNT"
        mount_point = os.path.join(chroot_path, mount)
        if not os.path.isdir(mount_point):
            die(f"Required chroot directory {chroot_path}/{mount} does not exist. Exiting.")
        if umount:
            action = "umount"
            mount_cmd = ["/bin/umount", "-R", f"{chroot_path}/{mount}"]
        else:
            mount_cmd = ["/bin/mount", "--rbind", f"/{mount}", f"{chroot_path}/{mount}"]
        if action == "mount" and os.path.ismount(mount_point):
            sys.stderr.write(GREEN + f" {action}: /{mount} (already mounted)\n")
        else:
            run_verbose(action, mount_cmd)


def main():
    sys.stderr.write(
        f"\nFuntoo fchroot {VERSION} (\"{NICK}\"); Copyright 2020-2022 Funtoo Solutions, Inc.\nLicensed under the Apache License, Version 2.0\n\n")
    if os.geteuid() != 0:
        sys.stderr.write("You must be root to fchroot. Exiting.\n")
        sys.exit(1)

    chroot_path = os.path.abspath(args.newroot)
    binaries_to_scan = ["/bin/su", "/bin/cp", "/bin/ps", "/bin/awk", "/bin/bash"]

    if commands:
        # Add the explicit thing we will be executing as something to scan to determine architecture:
        binaries_to_scan = commands[:1] + binaries_to_scan

    arch_desc = None
    for binary in binaries_to_scan:
        binary_path = os.path.join(chroot_path, binary.lstrip('/'))
        if os.path.exists(binary_path):
            arch_desc = get_arch_of_binary(binary_path)

    if arch_desc is None:
        die("Couldn't detect fchroot arch. Please specify path of executable within chroot to execute on command-line.")

    # ensure required qemu binary exists in /usr/bin on host:
    if not qemu_exists(arch_desc):
        die(f"Couldn't find qemu binary at {qemu_path(arch_desc)} Exiting.")

    # create /usr/local/bin in chroot if it doesn't exist:
    local_bin_path = os.path.join(chroot_path, "usr/local/bin")
    if not os.path.exists(local_bin_path):
        os.makedirs(local_bin_path)

    # copy static qemu binary into chroot from host:
    chroot_qemu_path = os.path.join(chroot_path, "usr/local/bin/", qemu_arch_settings[arch_desc]["qemu_binary"])
    if not os.path.exists(chroot_qemu_path):
        result = subprocess.run(["/bin/cp", qemu_path(arch_desc), chroot_qemu_path])
        if result.returncode != 0:
            die("Unable to copy qemu into chroot. Exiting.")

    # create C wrapper, and compile it. Both will end up in /usr/local/bin inside chroot:
    chroot_wrapper_path = os.path.join(chroot_path, "usr/local/bin")
    os.makedirs(chroot_wrapper_path, exist_ok=True)
    compile_wrapper(arch_desc, chroot_wrapper_path, qemu_cpu=args.cpu)

    # register binary format if it is not yet registered:
    if not is_binfmt_registered(arch_desc):
        register_binfmt(arch_desc, wrapper_path(arch_desc))

    # copy /etc/resolv.conf into chroot:
    action = "DNS"
    if os.path.exists("/etc/resolv.conf"):
        cmd_list = ["/bin/cp", "/etc/resolv.conf", os.path.join(chroot_path, "etc")]
        run_verbose(action, cmd_list)

    bind_mount(chroot_path)
    qemu_cpu = args.cpu if args.cpu else qemu_arch_settings[arch_desc]["qemu_cpu"]
    sys.stderr.write(GREEN + ">>> Entering " + CYAN + f"{arch_desc} ({qemu_cpu} CPU)" + END + " fchroot...\n")
    if args.preserve_env:
        env = os.environ
    else:
        env_whitelist = ["TERM"]
        env = {}
        for item in env_whitelist:
            env[item] = os.environ[item]
    env.update({"PS1": '\\033[01;33mfchroot\\033[0m \\$ '})
    # newer method where we wait in the background to undo the bind mounts.
    result = subprocess.run(['/bin/chroot'] + [args.newroot] + commands, env=env)
    bind_mount(chroot_path, umount=True)
    sys.stderr.write(CYAN + "<<< Exiting " + END + "fchroot.\n")
    sys.exit(result.returncode)


if __name__ == "__main__":
    main()

# vim: ts=4 sw=4 noet
