#!/bin/sh

set -e

SHELL_FOLDER=$(cd "$(dirname "$0")"; pwd)
CURRENT_FOLDER=bin
cd $SHELL_FOLDER

if [ -z "$SYSROOT" ]; then
    if [ -d "/mnt/userdata" ]; then
        export SYSROOT=/mnt
    else
        echo "ERROR: SYSROOT is not set, and /mnt/userdata does not exist."
        echo "Please mount RV1126B rootfs to /mnt or export SYSROOT=/path/to/board/rootfs."
        exit 1
    fi
fi

if [ -z "$CXX" ]; then
    if command -v arm-linux-gnueabihf-g++ >/dev/null 2>&1; then
        export CXX=arm-linux-gnueabihf-g++
    elif command -v arm-rockchip830-linux-uclibcgnueabihf-g++ >/dev/null 2>&1; then
        export CXX=arm-rockchip830-linux-uclibcgnueabihf-g++
    elif command -v aarch64-linux-gnu-g++ >/dev/null 2>&1; then
        export CXX=aarch64-linux-gnu-g++
    else
        echo "ERROR: No cross C++ compiler found."
        echo "Please set CXX manually, for example:"
        echo "  CXX=arm-linux-gnueabihf-g++ ./build.sh"
        exit 1
    fi
fi

echo "SHELL_FOLDER=$SHELL_FOLDER"
echo "CURRENT_FOLDER=$CURRENT_FOLDER"
echo "SYSROOT=$SYSROOT"
echo "CXX=$CXX"

# clear
if [ "$1" = "clear" ]; then
    rm -rf build
    rm -rf Release
    exit 0
fi

# build
rm -rf build
mkdir build
cd build

cmake .. \
    -DCMAKE_SYSTEM_NAME=Linux \
    -DCMAKE_CXX_COMPILER="$CXX"

make -j24

cd ..

# release
mkdir -p Release
rm -f Release/test-*
cp build/test-* Release/
chmod 777 Release/test-*

# copy to board
mkdir -p "$SYSROOT/userdata/ppocrv6_ocr_demo/$CURRENT_FOLDER"

if [ "$1" = "cpres" ]; then
    cp Release/* "$SYSROOT/userdata/ppocrv6_ocr_demo/$CURRENT_FOLDER/"
else
    cp Release/test-* "$SYSROOT/userdata/ppocrv6_ocr_demo/$CURRENT_FOLDER/"
fi

echo "Release files:"
ls -lh Release

echo "Copied to:"
echo "$SYSROOT/userdata/ppocrv6_ocr_demo/$CURRENT_FOLDER"
