#!/bin/sh

# ----- Start commands -----

fatal_err() {
    echo -e "\033[31mFatal error $*\033[0m"
}

# -----  End commands  -----



# ----- Start safeguards -----

if [[ "$1" != '-a' ]]; then
    fatal_err
    echo "  This script will potentially break any existing instance of Pairent."
    echo "  To execute this script, re-run it with option -a as first argument."
    exit -1
fi

if ! [ -f .env ]; then
    fatal_err
    echo -e "  No .env file was found."
    echo -e "  Please use the \033[32m.env.example\033[0m to create a dotenv file:"
    echo -e "    1. \033[34mcp .env.example .env\033[0m"
    echo -e "    2. Edit your \033[32m.env\033[0m in your favourite editor"
    exit -1
fi

# -----  End safeguards  -----



# ----- Start bootstrap front -----

echo Building frontend static files...

cd pairent_frontend_react

NPMS=('npm' 'pnpm' 'yarn')
NPM='None'

for n in ${NPMS[@]}; do
    if [ -x "$(command -v "$n")" ]; then
        NPM=$n
    fi
done

if [[ "$NPM" == 'None' ]]; then
    fatal_err
    echo '  No node package manager was found in your system.'
    echo '  Please install one of the following:'
    for n in ${NPMS[@]}; do
        echo -e "    $n"
    done
    exit -1
fi

rm -rf node_modules

$NPM install
$NPM run build

DIST_FOLDER=$(realpath dist)

cd ..
cp -r $DIST_FOLDER/* static
cp $DIST_FOLDER/index.html pairent_backend/pairent_app/templates
cp $DIST_FOLDER/../public/* static -r

echo Done building frontend static files

# -----  End bootstrap front  -----