#!/bin/sh -e

cd `dirname "$0"`
ROOT=`pwd -P`
WEBPACK_ARGS=""

"$ROOT"/copy-migrations

OUTPUT_HASH="[hash]"
if [ $NODE_ENV == 'development' ]; then
    # Use a constant filename in development mode to make it easier to
    # rebuild the backend without having to rebuild the frontend
    OUTPUT_HASH="dev"
fi

# Clean out previous build files
rm -f ../lib-dist/browser/*
rm -rf ../../desktop-client/public/kcab

if [ $NODE_ENV == 'development' ]; then
  # In dev mode, always enable watch mode and symlink the build files.
  # Make sure to do this before starting the build since watch mode
  # will block
  WEBPACK_ARGS="$WEBPACK_ARGS --watch"
  ln -snf "$ROOT"/../lib-dist/browser ../../desktop-client/public/kcab
fi

../node_modules/.bin/webpack --config ../webpack/webpack.browser.config.js \
  --target "webworker" \
  --output-filename "kcab.worker.$OUTPUT_HASH.js" \
  --output-chunkfilename "[id].[name].kcab.worker.$OUTPUT_HASH.js" \
  --progress \
  $WEBPACK_ARGS


if [ $NODE_ENV == 'production' ]; then
  # In production, just copy the built files
  mkdir ../../desktop-client/public/kcab
  cp -r ../lib-dist/browser/* ../../desktop-client/public/kcab
fi