#!/usr/bin/env python3

# SPDX-FileCopyrightText: 2020 The P4 Language Consortium
#
# SPDX-License-Identifier: Apache-2.0

""" This programs builds a bpftool binary and the libbpf static library and places it in the runtime
    folder. The library and its headers are required by the kernel target.
"""

import sys
import logging
from pathlib import Path

FILE_DIR = Path(__file__).resolve().parent
# Append tools to the import path.
sys.path.append(str(FILE_DIR.joinpath("../../tools")))
import testutils


def main() -> int:
    # Configure logging.
    logging.basicConfig(
        format="%(levelname)s:%(message)s",
        level=logging.WARN,
        filemode="w",
    )
    bpftool_dir = FILE_DIR.joinpath("runtime/contrib/bpftool")
    bpftool_src_dir = bpftool_dir.joinpath("src")
    bpftool_build_dir = bpftool_src_dir.joinpath("build")
    bpftool_target_dir = FILE_DIR.joinpath("runtime/install/")
    bpftool_target_dir.mkdir(parents=True, exist_ok=True)
    # Create the bpftool build directory
    testutils.check_and_create_dir(bpftool_build_dir)
    # Build bpftool
    mk_cmd = f"make -C {bpftool_src_dir} install "
    mk_cmd += f"OUTPUT={bpftool_target_dir}/ "
    mk_cmd += "BUILD_STATIC_ONLY=y "
    mk_cmd += f"OBJDIR={bpftool_build_dir} "
    mk_cmd += f"DESTDIR={bpftool_target_dir} "
    mk_cmd += "EXTRA_CFLAGS=-fPIE"
    print(mk_cmd)
    result = testutils.exec_process(args=mk_cmd)
    if result.returncode != testutils.SUCCESS:
        testutils.log.error("Could not build bpftool")
    return result.returncode


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