#!/usr/bin/env bash
# This script is run by the webcom user on the server 

set -ex
ulimit -u 512

BUILD_DIR=/users/webcom/live-deploys/eventer-build
LIVE_DIR=/users/webcom/live-deploys/eventer
GIT_LINK=https://git.csclub.uwaterloo.ca/www/Eventer 
ENV_FILE=/users/webcom/live-deploys/eventer-secrets/.env
BRANCH_NAME=master

# Build eventer in build dir
rm -rf $BUILD_DIR
git clone --single-branch --branch $BRANCH_NAME $GIT_LINK --depth=1 $BUILD_DIR 
cd $BUILD_DIR 
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
cp -r $BUILD_DIR/. $LIVE_DIR
cp $ENV_FILE $LIVE_DIR/.env
cd $LIVE_DIR
npm run pm2:start