#!/bin/bash

cross_compile=false
build_hisi=false
debug_deploy=false
TARGET_IP="172.16.104.49"
TARGET_PATH="/system/bin"
base_path=$(pwd)
libraries_root="/opt/Libraries"
if [ $base_path==/home/* ]; then
    build_path=${base_path}/build
else
    build_path=/tmp/build
fi
echo "build directory: $build_path"

function cmake_scan() {
    if [ $cross_compile = true ]; then
        toolchain_file=-DCMAKE_TOOLCHAIN_FILE=resources/cmake/toolchain.cmake
    else
        toolchain_file="-DCROSS_BUILD=OFF"
    fi
    if [ ! -d ${build_path} ]; then
        mkdir ${build_path}
    fi

    if [ $debug_deploy = true ]; then
        build_debug=-DCMAKE_BUILD_TYPE=Debug
    else
        build_debug=""
    fi

    cmake \
        -G Ninja \
        -S ${base_path} \
        -B ${build_path} \
        $build_debug \
        $toolchain_file
}

function qtmoc() {
    MOC_EXE="docker run --rm -v $(pwd):$(pwd) -w $(pwd) frp-by1.wwvvww.cn:45288/ubuntu_dev:16.04 moc"
    declare -a files=(
        "src/qt/mainUi/mainUi.h:src/qt/mainUi/moc_mainUi.cpp"
        "src/qt/utility/UiTools.h:src/qt/utility/moc_UiTools.cpp"
        "src/qt/recoUi/recoUi.h:src/qt/recoUi/moc_recoUi.cpp"
        "src/qt/recoUi/recoUiRecognize.h:src/qt/recoUi/moc_recoUiRecognize.cpp"
        "src/qt/recoUi/recoUiRecognizeTypeBase.h:src/qt/recoUi/moc_recoUiRecognizeTypeBase.cpp"
        "src/qt/recoUi/recoUiCallConsole.h:src/qt/recoUi/moc_recoUiCallConsole.cpp"
        "src/qt/recoUi/recoUiCallDial.h:src/qt/recoUi/moc_recoUiCallDial.cpp"
        "src/qt/utility/DndModeCountDownItem.h:src/qt/utility/moc_DndModeCountDownItem.cpp"
        "src/qt/mainUi/UvcView.h:src/qt/mainUi/moc_UvcView.cpp"
    )

    for file in "${files[@]}"; do
        IFS=":" read -r input output <<<"$file"

        if [[ -f $input ]]; then
            echo "Processing $input..."
            $MOC_EXE "$input" -o "$output"
        else
            echo "Warning: $input does not exist. Skipping..."
        fi
    done
}

function build() {
    if [ ! -f "${build_path}/CMakeCache.txt" ]; then
        cmake_scan
    fi
    if [ $? -ne 0 ]; then
        exit 1
    fi
    cmake \
        --build ${build_path} \
        --target all
    if [ $? -ne 0 ]; then
        exit 1
    fi

    if [ $cross_compile = true ]; then
        deploy
    fi
}

function deploy() {
    # export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/system/lib
    if [ -n "$1" ]; then
        TARGET_IP=$1
    fi

    if [ $debug_deploy = true ]; then
        TARGET_PATH="/data/sdcard"
    fi

    echo "deploy to target $TARGET_IP, path: ${TARGET_PATH} ..."
    ssh -i resources/ssh_host_rsa_key_ok root@${TARGET_IP} "mount -o remount rw /system/; mount -o remount rw /"
    ssh -i ~/Projects/ssh_host_rsa_key_ok root@${TARGET_IP} "killall start-app.sh; pgrep -f GateFace | xargs kill -s 9"
    ssh -i resources/ssh_host_rsa_key_ok root@${TARGET_IP} "pgrep -f VoucherVerifyServer | xargs kill -s 9"
    ssh -i resources/ssh_host_rsa_key_ok root@${TARGET_IP} "pgrep -f Record | xargs kill -s 9"

    scp -i resources/ssh_host_rsa_key_ok ${build_path}/Record/Record root@${TARGET_IP}:/sdcard/
    ssh -i resources/ssh_host_rsa_key_ok root@${TARGET_IP} "sync"

    # ssh -i resources/ssh_host_rsa_key_ok root@${TARGET_IP} "echo 116 > /sys/class/gpio/export"
    # ssh -i resources/ssh_host_rsa_key_ok root@${TARGET_IP} "echo out > /sys/class/gpio/gpio116/direction"
    # ssh -i resources/ssh_host_rsa_key_ok root@${TARGET_IP} "echo 1 > /sys/class/gpio/gpio116/value"

    if [ $debug_deploy != true ]; then
        echo "reboot remote device."
        ssh -i resources/ssh_host_rsa_key_ok root@${TARGET_IP} "reboot"
    fi
}

function clean() {
    if [ -d ${build_path} ]; then
        rm -fr ${build_path}
    fi
}

function initialize() {
    if [ -n "$1" ]; then
        TARGET_IP=$1
    fi
    APP_DIR=$(dirname "$(dirname "$(readlink -f $0)")")
    SSH_KEY=$(cat ~/.ssh/id_rsa.pub)
    echo "ssh copy id to ${TARGET_IP} ..."
    ssh -i ~/.ssh/ssh_host_rsa_key_ok root@${TARGET_IP} "mount -o remount rw /system; mount -o remount rw /oem; mount -o remount rw /"
    ssh -i ~/.ssh/ssh_host_rsa_key_ok root@${TARGET_IP} "grep -q 'mount -o remount rw' /etc/profile || echo 'mount -o remount rw /system; mount -o remount rw /oem; mount -o remount rw /' >> /etc/profile"
    ssh -i ~/.ssh/ssh_host_rsa_key_ok root@${TARGET_IP} "if [ ! -f /usr/bin/scp ]; then cp /oem/bin/scp /usr/bin/; else echo 'scp exist'; fi"
    ssh -i ~/.ssh/ssh_host_rsa_key_ok root@${TARGET_IP} "printf '%s\n' '${SSH_KEY}' | grep -qxFf - /oem/.ssh/authorized_keys || echo '${SSH_KEY}' >> /oem/.ssh/authorized_keys"
    ssh -i ~/.ssh/ssh_host_rsa_key_ok root@${TARGET_IP} "test -e /sdcard/gdbserver || exit 1" && scp -i ~/.ssh/ssh_host_rsa_key_ok /opt/gcc-arm-8.3-2019.03-x86_64-arm-linux-gnueabihf/arm-linux-gnueabihf/libc/usr/bin/gdbserver root@${TARGET_IP}:/sdcard
    ssh -i ~/.ssh/ssh_host_rsa_key_ok root@${TARGET_IP} "test -e /sdcard/gdb || exit 1" && scp -i ~/.ssh/ssh_host_rsa_key_ok /mnt/e/Documents/瑞为/FacePass/gdb-rk root@${TARGET_IP}:/sdcard/gdb

    ssh -i ~/.ssh/ssh_host_rsa_key_ok root@${TARGET_IP} "sync"

    file="src/gate_face/Makefile.mak"
    if ! grep -q "/opt/gcc-arm-8.3-2019.03-x86_64-arm-linux-gnueabihf" $file; then
        awk -v n=157 -v text='
    INCLUDES += -I/opt/gcc-arm-8.3-2019.03-x86_64-arm-linux-gnueabihf/lib/boost_1_86_0/include
    INCLUDES += -I/opt/gcc-arm-8.3-2019.03-x86_64-arm-linux-gnueabihf/lib/nng-1.9.0/include
    LDFLAGS += -L/opt/gcc-arm-8.3-2019.03-x86_64-arm-linux-gnueabihf/lib/nng-1.9.0/lib -lnng
    LDFLAGS += -L/opt/gcc-arm-8.3-2019.03-x86_64-arm-linux-gnueabihf/lib/mbedtls-3.6.2/lib -lmbedtls -lmbedcrypto -lmbedx509 -lp256m -leverest
    ' 'NR==n{print text}1' $file > $file.tmp && mv $file.tmp $file
    fi

    target_dir="src/gate_face"
    if [ ! -f "$target_dir/NngDebuger.h" ]; then
        cp "$APP_DIR/NngDebuger/NngDebuger.h" "$target_dir/"
        cp "$APP_DIR/NngDebuger/NngDebuger.cpp" "$target_dir/"
    fi

    file="src/gate_face/Makefile"
    if ! grep -q "NngDebuger.o" $file; then
        sed -i '/^OBJS := /s/$/ NngDebuger.o/' $file
    fi

}

function build_old() {
    # start-app.sh 以下就可以让应用不开机自启
    # d_state=0
    # l_state=0
    # n_state=1
    # i_state=1
    if [ -n "$1" ]; then
        TARGET_IP=$1
    fi

    if [ $debug_deploy = true ]; then
        TARGET_PATH="/data/sdcard"
    fi

    qtmoc
    # if [ $? -ne 0 ]; then
    #     exit 1
    # fi

    if [ $build_hisi = true ]; then
        docker run -it --rm --user 1000:1000 -v /opt:/opt -v $(pwd):$(pwd) -w $(pwd) frp-by1.wwvvww.cn:45288/nanopb:0.3.9.3 make server_protocol
        docker run -it --rm --user 1000:1000 -v /opt:/opt -v $(pwd):$(pwd) -w $(pwd) frp-by1.wwvvww.cn:45288/nanopb:0.3.9.3 make -j4
    else
        docker run -it --rm --user 1000:1000 -v /opt:/opt -v $(pwd):$(pwd) -w $(pwd) -e PATH="/opt/gcc-arm-8.3-2019.03-x86_64-arm-linux-gnueabihf/bin:$PATH" frp-by1.wwvvww.cn:45288/nanopb:0.3.9.3 make PLATFORM=rv1109 server_protocol
        make PLATFORM=rv1109 -j4
    fi
    if [ $? -ne 0 ]; then
        exit 1
    fi
    deploy_old $TARGET_IP
    # deploy_old "172.16.103.98"
    # deploy_old "172.16.103.117"
}

function deploy_old() {
    # killall start-app.sh; ps | grep GateFace | grep -v "grep" | awk '{print $1}' | xargs kill -s 9 
    if [ -n "$1" ]; then
        TARGET_IP=$1
    fi
    echo "deply to $TARGET_IP, path $TARGET_PATH"
    ssh -i ~/.ssh/ssh_host_rsa_key_ok root@${TARGET_IP} "mount -o remount rw /; mount -o remount rw /system/"

    if [ $build_hisi = true ]; then
        ssh -i ~/.ssh/ssh_host_rsa_key_ok root@${TARGET_IP} "killall start-app.sh; killall GateFace; sleep 1"
        ssh -i ~/.ssh/ssh_host_rsa_key_ok root@${TARGET_IP} "killall start-app.sh; killall GateFace"
        ssh -i ~/.ssh/ssh_host_rsa_key_ok root@${TARGET_IP} "killall start-app.sh; killall GateFace"
    else
        ssh -i ~/.ssh/ssh_host_rsa_key_ok root@${TARGET_IP} "killall start-app.sh; killall GateFace;"
    fi
    # scp -r -i  ~/.ssh/ssh_host_rsa_key_ok src/web/php/*.php root@${TARGET_IP}:/system/www/web/
    # scp -r -i ~/Projects/ssh_host_rsa_key_ok resources/audio/*.wav root@${TARGET_IP}:/system/audio
    scp -i ~/.ssh/ssh_host_rsa_key_ok ./build/GateFace root@${TARGET_IP}:$TARGET_PATH
    # scp -i ~/Projects/ssh_host_rsa_key_ok resources/language/FaceTick_EN.qm root@${TARGET_IP}:/system/language
    # scp -i ~/Projects/ssh_host_rsa_key_ok ./build/netconfig root@${TARGET_IP}:$TARGET_PATH

    if [ $build_hisi = true ]; then
        scp  -i ~/.ssh/ssh_host_rsa_key_ok ./3rdparty/arm-himix200-linux/rwStageProtocol/lib/librwSrvProtocol.so root@${TARGET_IP}:/system/lib/
        ssh -i ~/.ssh/ssh_host_rsa_key_ok root@${TARGET_IP} "reboot"
    else
        # scp -i ~/Projects/ssh_host_rsa_key_ok ./3rdparty/arm-linux-gnueabihf/librwhscheckpw/lib/librwhscheckpw.so root@${TARGET_IP}:/system/lib/
        scp -i ~/.ssh/ssh_host_rsa_key_ok ./3rdparty/arm-linux-gnueabihf/rwStageProtocol/lib/librwSrvProtocol.so root@${TARGET_IP}:/system/lib/
        # scp -i ~/Projects/ssh_host_rsa_key_ok ./3rdparty/arm-linux-gnueabihf/ffmepg/lib/libavdevice.so.58 root@${TARGET_IP}:/system/lib/
        # scp -i ~/Projects/ssh_host_rsa_key_ok ./3rdparty/arm-linux-gnueabihf/ffmepg/lib/libavfilter.so.7 root@${TARGET_IP}:/system/lib/
        # scp -i ~/Projects/ssh_host_rsa_key_ok ./3rdparty/arm-linux-gnueabihf/ffmepg/lib/libavformat.so.58 root@${TARGET_IP}:/system/lib/
        # scp -i ~/Projects/ssh_host_rsa_key_ok ./3rdparty/arm-linux-gnueabihf/ffmepg/lib/libavutil.so.56 root@${TARGET_IP}:/system/lib/
        # scp -i ~/Projects/ssh_host_rsa_key_ok ./3rdparty/arm-linux-gnueabihf/ffmepg/lib/libswresample.so.3 root@${TARGET_IP}:/system/lib/
    fi

    ssh -i ~/.ssh/ssh_host_rsa_key_ok root@${TARGET_IP} "sync"

    if [ $debug_deploy = false ]; then
        if [ $build_hisi = false ]; then
            ssh -i ~/.ssh/ssh_host_rsa_key_ok root@${TARGET_IP} "echo 1 > /dev/watchdog"
        fi
    fi
}

function main() {
    local cmd=$1
    shift 1
    case $cmd in
    build)
        build
        ;;
    scan)
        cmake_scan
        ;;
    clean)
        clean
        ;;
    old)
        build_old $@
        ;;
    init)
        initialize $@
        ;;
    *)
        build
        ;;
    esac
}

main $@
