#!/usr/bin/env bash

export LC_ALL=C

function checkfail {
    if [[ $1 -ne 0 ]]; then
        echo "An error occurred,"
        echo "press enter to exit."
        read -rs dummy
        exit "$1"
    fi
}

function finish {
    echo "Done."
    echo "Thank you for installing ckb-next!"
    exit 0
}

# Check if we're in the right directory
if [[ ! -f "src/daemon/usb.c" ]]; then
    echo "Please run this script inside the ckb-next source directory."
    exit
fi

rm -rf build

cmake -H. -Bbuild -DCMAKE_BUILD_TYPE=Release -DSAFE_INSTALL=ON -DSAFE_UNINSTALL=ON
checkfail $?

# Find out how many cores the system has, for make
JOBS=$(getconf _NPROCESSORS_ONLN 2>/dev/null)

# Default to 2 jobs if something went wrong earlier
if [[ -z "$JOBS" ]]; then
    JOBS=2
fi

cmake --build build --target all -- -j "$JOBS"
checkfail $?

sudo cmake --build build --target install
checkfail $?

finish
