#!/bin/bash

####################################################################################
# Original author: bewillia							   #
# Created date:	   11/2017							   #
####################################################################################
# This script was made to automate the deployment process.
# It was made to run inside the webapps directory.
# If you switch directories, you must also make sure the variable paths are updated.
#
#
# After it removes the old .war file, 
# the user is responsible for uploading the new .war file to this directory.
# The user is also responsible for entering the password when the server restarts. 
#
# to run: 
# 	./redeploy
#
# If you updated any domains, you will have to flush the database,
# and reupload any test data,
# otherwise deployment will fail due to database errors.
# to do this, run this script with the -f or --flush flag: 
#
# 	./redeploy -f
# OR
# 	./redeploy --flush
#
# If you use my script for your project,
# you will have to modify the variables 
# so they correspond to your own project. 
####################################################################################

DB="../db/*.db"			# relative to the webapps folder.
DIR="ACL"
WAR="ACL.war"
SERV="tomcat@2017_sd_5"

# FLAG CHECK #
if [ -n "$1" ]; 
then
	if [ "$1" == "-f" ] || [ "$1" == "--flush" ];
	then
		echo Flushing database...
		echo `rm -rf $DB`
	else
		echo -e $1 is an invalid flag. '\n'
		echo To run script: 
		echo -e '\t' ./redeploy '\n'
		echo To flush database:
		echo -e '\t' ./redeploy -f 
		echo OR 
		echo -e '\t' ./redeploy --flush '\n'
		exit
	fi
fi 

# REDEPLOYMENT PROCESS #
echo `rm $WAR`

echo Old .war removed. Please upload new .war.

sleep 10s

echo -n Waiting for new .war to explode..

# appends . to the message so it doesn't look like the script is stuck.
while [  ! -d $DIR ];
do
	echo -n .
	sleep 3
done

echo -e '\n'

echo $WAR exploded!

sleep 1

echo Updating permissions...

echo `chmod 664 $WAR`

echo Restarting server...

echo `sudo systemctl restart $SERV` 

echo Done.

