#!/usr/bin/env python3
"""Build SQLite's upstream C test programs and create Graal launch commands."""

import argparse
import os
from pathlib import Path
import shlex
import shutil
import subprocess
import sys


ROOT = Path(__file__).resolve().parents[1]
DEFAULT_PROGRAMS = ("testfixture", "sqlite3", "threadtest3", "mptester", "speedtest1")
PROGRAMS = (*DEFAULT_PROGRAMS, "threadtest5", "fuzzcheck", "sessionfuzz", "sqldiff", "dbhash")


def tool(environment, executable):
    found = shutil.which(os.environ.get(environment, executable))
    if found is None:
        raise ValueError(f"cannot find {os.environ.get(environment, executable)}")
    return Path(found).absolute()


def build(args):
    source = args.source.resolve(strict=True)
    build_dir = args.build.resolve()
    native = build_dir / "native"
    guest = build_dir / "guest"
    native.mkdir(parents=True, exist_ok=False)
    guest.mkdir()

    compiler = tool("GRAAL_CLANG", "clang")
    archiver = tool("GRAAL_LLVM_AR", "llvm-ar")
    runner = args.runner.resolve()
    env = dict(os.environ, PATH=f"{compiler.parent}{os.pathsep}{os.environ.get('PATH', '')}")
    configure = ["sh", str(source / "configure"), "--disable-shared", "--disable-readline"]
    if args.with_tcl:
        configure.append(f"--with-tcl={args.with_tcl.resolve(strict=True)}")
    if args.with_tclsh:
        configure.append(f"--with-tclsh={args.with_tclsh.resolve(strict=True)}")
    configure.extend(args.configure_arg)
    subprocess.run(configure, cwd=native, check=True, env=env)

    programs = args.program or DEFAULT_PROGRAMS
    subprocess.run(
        ["make", "-j", str(args.jobs),
         f"CC={shlex.quote(str(compiler))} --target={shlex.quote(args.target)} -flto=full",
         f"AR={shlex.quote(str(archiver))}", f"CFLAGS={args.cflags}",
         "T.link.gcov=-fuse-ld=lld -Wl,--save-temps", *programs],
        cwd=native, check=True, env=env,
    )
    modules = {name: native / f"{name}.0.0.preopt.bc" for name in programs}
    for module in modules.values():
        with module.open("rb") as stream:
            if stream.read(4) != b"BC\xc0\xde":
                raise ValueError(f"expected LLD's merged LLVM bitcode at {module}")
    for name, module in modules.items():
        wrapper = guest / name
        command = shlex.join((str(runner), "--run-module"))
        libraries = shlex.quote(f"--libraries={args.libraries}")
        wrapper.write_text(
            f'#!/bin/sh\nexec {command} --argv0="$0" {libraries} {shlex.quote(str(module))} "$@"\n',
            encoding="utf-8",
        )
        wrapper.chmod(0o755)
    print(guest)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("source", type=Path, help="SQLite canonical source tree")
    parser.add_argument("build", type=Path, help="build location without an existing native subdirectory")
    parser.add_argument("--with-tcl", type=Path, help="directory containing tclConfig.sh")
    parser.add_argument("--with-tclsh", type=Path)
    parser.add_argument("--configure-arg", action="append", default=[], metavar="OPTION")
    parser.add_argument("--cflags", default="-O0 -g0", help="CFLAGS passed to the upstream build")
    parser.add_argument("--program", action="append", choices=PROGRAMS)
    parser.add_argument("--runner", type=Path, default=ROOT / "dist" / "sqlite-api-shell")
    parser.add_argument("--target", default=os.environ.get("GRAAL_C_TARGET", "x86_64-unknown-linux-gnu"))
    parser.add_argument("--libraries", default="libtcl8.6.so:libz.so.1:libm.so.6")
    parser.add_argument("-j", "--jobs", type=int, default=2)
    args = parser.parse_args()
    if args.jobs < 1:
        parser.error("jobs must be positive")
    try:
        build(args)
    except (OSError, ValueError, subprocess.CalledProcessError) as failure:
        print(f"build-upstream: {failure}", file=sys.stderr)
        return 1
    return 0


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