#!/usr/bin/env bash
# This script is meant to be copied to ~/bin/deploy-eventcentral.sh on the
# webcom account on caffeine.csclub.uwaterloo.ca, and run from there by Drone
# CI (see .drone.yml). Mirrors www/Eventer's deploy.sh, adapted for
# EventCentral's backend/frontend monorepo layout -- only the backend gets
# deployed here; the frontend in this repo is a local test harness, not a
# production service (see README).

set -ex
ulimit -u 512

BUILD_DIR=/users/webcom/live-deploys/eventcentral-build
LIVE_DIR=/users/webcom/live-deploys/eventcentral
GIT_LINK=https://git.csclub.uwaterloo.ca/www/EventCentral
ENV_FILE=/users/webcom/live-deploys/eventcentral-secrets/.env
BRANCH_NAME=main

# Build in a scratch dir
rm -rf "$BUILD_DIR"
git clone --single-branch --branch "$BRANCH_NAME" "$GIT_LINK" --depth=1 "$BUILD_DIR"
cd "$BUILD_DIR/backend"
npm install
npm run compile
rm -rf "$BUILD_DIR/.git"

# Stop old pm2 process
# || true prevents the script from exiting because of status code 1 if the
# process is not running
npm run pm2:delete:noerror || true

# Copy build dir to live dir and start pm2 again
rm -rf "$LIVE_DIR" || true
mkdir -p "$LIVE_DIR"
cp -r "$BUILD_DIR/backend/." "$LIVE_DIR"
cp "$ENV_FILE" "$LIVE_DIR/.env"
cd "$LIVE_DIR"
npm run pm2:start
