#!/bin/bash
#
# Copyright (c) 2020 Bubble, Inc.  All rights reserved. For personal (non-commercial) use, see license: https://getbubblenow.com/bubble-license/
#
#
# Prepares the bubble.jar file for active usage.
#
# 1. Copy scripts to bubble-server/target/classes/scripts
#
# 2. If the environment variable INSTALL_WEB is equal to "web", also build and install the bubble-web
#    site to bubble-server/target/classes/site
#
# Usage:
#
#   prep_bubble_jar
#
# Environment variables:
#
#   INSTALL_WEB       : if this is equal to 'web' then the frontend will be built and included in the jar
#   DEBUG_BUILD       : if this is equal to 'debug' then nothing will be done, the jar will be left as-is
#   BUBBLE_PRODUCTION : if this is set to anything, then a production build will be made.
#
SCRIPT="${0}"
SCRIPT_DIR=$(cd $(dirname ${SCRIPT}) && pwd)
. ${SCRIPT_DIR}/bubble_common

if [[ ! -z "${DEBUG_BUILD}" && "${DEBUG_BUILD}" == "debug" ]] ; then
  echo "DEBUG_BUILD is set, not doing anything further"
  exit 0
fi

BUBBLE_SERVER="$(cd "${SCRIPT_DIR}/../bubble-server" && pwd)"
CLASSES_DIR="${BUBBLE_SERVER}/target/classes"

if [[ -z "${BUBBLE_JAR}" ]] ; then
  die "bubble jar not found: ${BUBBLE_JAR}"
fi

mkdir -p ${CLASSES_DIR}/scripts
for script in $(cat ${BUBBLE_SERVER}/src/main/resources/ansible/bubble_scripts.txt) ; do
  cp ${SCRIPT_DIR}/${script} ${CLASSES_DIR}/scripts || die "Error copying ${SCRIPT_DIR}/${script} -> ${CLASSES_DIR}/scripts"
done

cd ${CLASSES_DIR} && jar uvf ${BUBBLE_JAR} scripts || die "Error updating ${BUBBLE_JAR} with scripts"

if [[ ! -z "${BUBBLE_PRODUCTION}" || ( ! -z "${INSTALL_WEB}" && "${INSTALL_WEB}" == "web" ) ]] ; then
  mkdir -p ${CLASSES_DIR}/site
  BUBBLE_WEB="$(cd "${SCRIPT_DIR}/../bubble-web" && pwd)"
  if [[ ! -z "${BUBBLE_PRODUCTION}" ]] ; then
    WEBPACK_OPTIONS="--mode=production"
  else
    WEBPACK_OPTIONS=""
  fi
  cd ${BUBBLE_WEB} && npm install && webpack ${WEBPACK_OPTIONS} || die "Error building bubble-web"
  cp -R ${BUBBLE_WEB}/dist/* ${CLASSES_DIR}/site/ || die "Error copying ${BUBBLE_WEB}/dist/* -> ${CLASSES_DIR}/site/"
  cd ${CLASSES_DIR} && jar uvf ${BUBBLE_JAR} site || die "Error updating ${BUBBLE_JAR} with site"
  echo "Installed bubble-web to ${CLASSES_DIR}/site/"
fi
