#!/bin/sh

set -e

if [ ! -f "/homehub_workspace/package.json" ]; then
    echo "$0: Initializing the workspace at /homehub_workspace"
    (
        cd /;
        /homehub_var/virtualenv/bin/cookiecutter --no-input -f -s /homehub-workspace;
    )
fi

if [ -d "/homehub_workspace/docker-entrypoint.d/" ]; then
    echo "$0: Executing setup scripts at /homehub_workspace/docker-entrypoint.d"
    find "/homehub_workspace/docker-entrypoint.d/" -follow -type f -print | sort -n | while read -r f; do
        case "$f" in
            *.sh)
                if [ -x "$f" ]; then
                    echo "$0: Executing $f";
                    "$f"
                fi
                ;;
            *) ;;
        esac
    done
fi

(
    echo "$0: Installing backend dependencies at /homehub_workspace";
    cd /homehub_workspace;
    /homehub_var/virtualenv/bin/pip install -r requirements.txt;
)

SHOULD_BUILD_FRONTEND=1
if [ -f "/homehub_var/stamp_frontend.txt" ]; then
    SHOULD_BUILD_FRONTEND=`sha256sum -s -c "/homehub_var/stamp_frontend.txt"; echo $?`
fi

if [ $SHOULD_BUILD_FRONTEND -eq 1 ]; then
    echo "$0: Building and stamping the frontend at /homehub_workspace"
    (
        cd /homehub_workspace;
        yarn --modules-folder $YARN_MODULES_FOLDER install --prod --pure-lockfile;
        yarn --modules-folder $YARN_MODULES_FOLDER run webpack-cli;
        sha256sum "/homehub_workspace/package.json" "/homehub_workspace/settings.js" > "/homehub_var/stamp_frontend.txt";
    )
fi

exec "$@"
