#!/usr/bin/env bash

help()
{
echo ""
echo "SmartSim Setup"
echo "--------------"
echo ""
echo "[ARGVARS...] smartsim_setup [cpu|gpu] [--help|help]"
echo ""
echo "Argument variables:"
echo " PT=1               Build PyTorch backend"
echo " TF=1               Build TF backend"
echo " TFL=0              Build TFLite backend"
echo " ONNX=0             Build ONNX backend (linux only)"
echo ""
echo "Example: smartsim_setup cpu          (PT and TF on cpu)"
echo "Example: TFL=1 smartsim_setup gpu    (PT, TF, and TFL on gpu)"
echo ""
}

# Help output
if [[ $1 == --help || $1 == help || -z "$1" ]]; then
        help
        exit 0
fi

# Start installation script and set variables we need
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"
# set variables for RedisAI
RAI_BUILD_TYPE=${1:-"cpu"}
RAI_PT=${PT:-1}
RAI_TF=${TF:-1}
RAI_TFL=${TFL:-0}
RAI_ONNX=${ONNX:-0}

# Detect compute type
if [[ $1 == cpu ]]; then
        DEVICE="cpu"
elif [[ $1 == gpu ]]; then
        DEVICE="gpu"
fi

# Detect OS type
if [[ "$OSTYPE" == "linux"* ]]; then
        OS="linux"
elif [[ "$OSTYPE" == "darwin"* ]]; then
        OS="mac"
else
        OS="unknown"
fi

# catch silly users
if [[ $OS == "mac" && DEVICE == "gpu" ]]; then
        echo "WARNING: You are using a GPU on a Mac. This is not supported. Switching to CPU."
        DEVICE="cpu"
fi

# avoid wget warnings on macOS
[[ $OS == macos ]] && export LC_ALL=en_US.UTF-8


# make shared library dir
if [[ ! -d "$DIR/../lib" ]]; then
    mkdir $DIR/../lib
fi

# make clone directory location.
if [[ ! -d "$DIR/../.third-party" ]]; then
    mkdir $DIR/../.third-party
fi


# Stage 1: build Redis
$DIR/scripts/build-redis.sh
if [ $? != 0 ]; then
    echo "ERROR: Redis failed to build"
    exit 1
fi

# Stage 2: Build RedisAI
if [[ $RAI_BUILD_TYPE == "gpu" ]]; then
    source $DIR/scripts/build-redisai-gpu.sh $RAI_PT $RAI_TF $RAI_TFL $RAI_ONNX
    if [ $? != 0 ]; then
        echo "ERROR: RedisAI GPU failed to build"
        exit 1
    fi
else
    source $DIR/scripts/build-redisai-cpu.sh $RAI_PT $RAI_TF $RAI_TFL $RAI_ONNX
    if [ $? != 0 ]; then
        echo "ERROR: RedisAI CPU failed to build"
        exit 1
    fi
fi

