abinfo "Setting up environment for building python-grpcio ..."
export GRPC_PYTHON_BUILD_WITH_CYTHON=1
export GRPC_PYTHON_BUILD_SYSTEM_OPENSSL=1
export GRPC_PYTHON_BUILD_SYSTEM_ZLIB=1
export GRPC_PYTHON_BUILD_SYSTEM_CARES=1
export GRPC_PYTHON_BUILD_SYSTEM_RE2=1
export GRPC_PYTHON_BUILD_SYSTEM_ABSL=1
export GRPC_PYTHON_BUILD_WITH_SYSTEMD=1
export GRPC_BUILD_WITH_BORING_SSL_ASM=0

abinfo "Building Python language binding for gRPC ..."
GRPC_PYTHON_LDFLAGS="$(pkg-config --libs protobuf)" \
    GRPC_PYTHON_CFLAGS="-fvisibility=hidden -fno-wrapv -fno-exceptions \
    -std=c++17 $(pkg-config --cflags protobuf)" \
    python3 -m build --wheel --no-isolation

abinfo "Building Python protobuf generator ..."
cd "$SRCDIR"/tools/distrib/python/grpcio_tools
mkdir grpc_root
ln -sv "$SRCDIR"/src "$SRCDIR"/tools/distrib/python/grpcio_tools/grpc_root/src
ln -sv "$SRCDIR"/include "$SRCDIR"/tools/distrib/python/grpcio_tools/grpc_root/include
ln -sv "$SRCDIR"/third_party "$SRCDIR"/tools/distrib/python/grpcio_tools/third_party
# FIXME: manully set GRPC_PYTHOON_CFLAGS leads to infinit loop `-Wnon-virtual-dtor -DNOMINMAX`
# currently does not make any negative effect, and I have no idea how to fix it
GRPC_PYTHON_LDFLAGS="$(pkg-config --libs protobuf) -lprotoc" \
    GRPC_PYTHON_CFLAGS="-fno-wrapv -frtti $(pkg-config --cflags protobuf)" \
    python3 -m build --wheel --no-isolation
cd "$SRCDIR"

abinfo "Installing Python language binding for gRPC ..."
python3 -m installer -d "$PKGDIR" "$SRCDIR"/dist/*.whl

abinfo "Installing Python protobuf generator ..."
python3 -m installer -d "$PKGDIR" \
    "$SRCDIR"/tools/distrib/python/grpcio_tools/dist/*.whl
