#!/bin/bash
#
# Copyright (c) 2020 Bubble, Inc.  All rights reserved. For personal (non-commercial) use, see license: https://getbubblenow.com/bubble-license/
#
#
# Usage:
#
#     bpatch [user@]hostname [norestart]
#
#  [user@]hostname  : the hostname of the bubble node to update. Optionally, also specify a username.
#                     Usually you will have an entry in ~/.ssh/config to set the username and ssh key
#  norestart        : If present, do not restart the API server after updating the jar file
#
# Patch the bubble.jar on a remote node.
# This script only works if the only classes that have changed are in the bubble-server codebase.
# If other classes have changed, use bpatchfull
#
# You install the JDK on the remote node first: apt install openjdk-11-jdk-headless
#
SCRIPT="${0}"
SCRIPT_DIR=$(cd $(dirname ${SCRIPT}) && pwd)
. ${SCRIPT_DIR}/bubble_common

HOST=${1:?no host provided}
NO_RESTART=${2}

BUBBLE_SERVER_DIR="${SCRIPT_DIR}/../bubble-server"
if [[ ! -d "${BUBBLE_SERVER_DIR}" ]] ; then
  die "bubble-server dir not found: ${BUBBLE_SERVER_DIR}"
fi
cd ${BUBBLE_SERVER_DIR}

mvn -DskipTests=true -Dcheckstyle.skip=true compile && rsync -avzc ./target/classes ${HOST}:/tmp/ | egrep -v '*/$' || die "Error recompiling classes"

if [[ ! -z "${NO_RESTART}" && "${NO_RESTART}" == "norestart" ]] ; then
  echo "Patching but not restarting..."
  ssh ${HOST} "cd /tmp && cp ~bubble/api/bubble.jar . && cd classes && jar uvf ../bubble.jar . | egrep -v '*/\(*' && cat ../bubble.jar > ~bubble/api/bubble.jar" || die "Error patching remote jar"
else
  echo "Patching and restarting..."
  ssh ${HOST} "cd /tmp && cp ~bubble/api/bubble.jar . && cd classes && jar uvf ../bubble.jar . | egrep -v '*/\(*' && cat ../bubble.jar > ~bubble/api/bubble.jar && supervisorctl restart bubble" || die "Error patching remote jar"
fi