#!/bin/bash

check_package_existence() {
    local package=$1
    if apt-cache show "$package" > /dev/null 2>&1; then
        echo "The software package $package is available in the apt repository."
        return 0
    else
        echo "The software package $package is not available in the apt repository."
        return 1
    fi
}

package_lists=("cmake" "gcc" "g++" "p7zip-full")

for item in "${package_lists[@]}"; do
    check_package_existence "$item"
    if [ "$?" == "1" ] ; then
        sudo apt install $item -y
    fi
done


core_count=$(nproc)
thread_count=$((core_count - 2))
if [ $thread_count -lt 1 ]; then
    thread_count=1
fi

mkdir host_build
pushd host_build
# cmake -DBUILD_SHARED_LIBS=ON -DCMAKE_INSTALL_PREFIX=`pwd`/install ..
cmake -DCMAKE_INSTALL_PREFIX=`pwd`/install ..
make -j$thread_count
make install
cp ../link_lib.txt ./install
popd


gcc_tool=(arm-linux-gnueabihf aarch64-linux-gnu)

for item in "${gcc_tool[@]}"; do
    mkdir $item
    pushd $item
    if [ ! -f "./toolchain.cmake" ] ; then
        cp ../toolchain.cmake .
        GCC_TOOL="$item-gcc"
        TARGET_ARCH=`$GCC_TOOL -dumpmachine | awk -F '-' '{print $1}'`
        INSTALL_DIR=`pwd`/install
        sed -i "\$a\set(CMAKE_SYSTEM_PROCESSOR $TARGET_ARCH)" toolchain.cmake
        sed -i "\$a\set(CMAKE_STAGING_PREFIX $INSTALL_DIR)" toolchain.cmake
        sed -i "\$a\set(CMAKE_C_COMPILER $item-gcc)" toolchain.cmake
        sed -i "\$a\set(CMAKE_CXX_COMPILER $item-g++)" toolchain.cmake
    fi
    cmake -DCMAKE_TOOLCHAIN_FILE=./toolchain.cmake -DgRPC_BUILD_CODEGEN=OFF -DCMAKE_INSTALL_PREFIX=`pwd`/install ..
    make -j$thread_count
    make install
    cp ../link_lib.txt ./install
    popd
done
