#/bin/env bash

# 计算当前目录
CURRENT_DIR=$(cd `dirname $0`; pwd)
if [ "$(id -u)" -ne 0 ]; then
    SUDO="sudo"
fi

PKG_NAME="barrier_gate"

# 检查是否存在 aarch64-linux-gnu-gcc 和 aarch64-linux-gnu-g++ 不存在则安装
if ! which aarch64-linux-gnu-gcc > /dev/null 2>&1; then
    $SUDO apt-get install -y gcc-aarch64-linux-gnu
fi
if ! which aarch64-linux-gnu-g++ > /dev/null 2>&1; then
    $SUDO apt-get install -y g++-aarch64-linux-gnu
fi

build_target() {
    
    AARCH=$1

    # 进入 ${PKG_NAME} 目录，检查是否存在 build 目录，不存在则创建
    echo ">> Build <${PKG_NAME}> Now..."
    cd ${PKG_NAME}
    if [ -d build ]; then
        rm -rf build
    fi
    mkdir build && cd build
    CC=${AARCH}-linux-gnu-gcc CXX=${AARCH}-linux-gnu-g++ cmake -DCMAKE_BUILD_TYPE=Release .. >> /dev/null
    make -j4 >> /dev/null
    cd ${CURRENT_DIR}

    echo ">> Build <${PKG_NAME}> Done."

    # 进行打包处理
    if [ ! -d package ]; then
        mkdir package
    fi

    echo ">> Pack <${PKG_NAME}> Now..."
    if [ -d package/${PKG_NAME} ]; then
        rm -rf package/${PKG_NAME}
    fi

    mkdir -p package/${PKG_NAME}-${AARCH}
    cp -ra ${PKG_NAME}/build/${PKG_NAME} package/${PKG_NAME}-${AARCH}
    cp -ra ${PKG_NAME}/lib/${AARCH}/* package/${PKG_NAME}-${AARCH}
    cp -ra ${PKG_NAME}/config/config.json package/${PKG_NAME}-${AARCH}

    cd package && tar -zvcf ${PKG_NAME}-${AARCH}.tar.gz ${PKG_NAME}-${AARCH} >> /dev/null && rm -rf ${PKG_NAME}-${AARCH} && cd - >> /dev/null
}

build_target aarch64
build_target x86_64
echo '>> Build Done.'

cd ${CURRENT_DIR}

ls -lh package
