#!/bin/sh

PROJECT_NAME="off-admin-api"
EXTENSION="jar"
SPRING_PROFILE="dev"
PORT=18080

#fixed value
#it's okay to change it, but if you can, fix it.
USER="offline_was"
LOG_FILE_NAME="$PROJECT_NAME.log"
BUILD_FORDER="/home/$USER/$PROJECT_NAME"
BACKUP_FORDER="$BUILD_FORDER/backup"
DEPLOY_FORDER="$BUILD_FORDER/deploy"
FILE_ARCHIVE_DAY=7

if [ "`whoami`" != $USER ] ;
then
        echo "echo > not a valid user (hint : $USER)"
else
        if [ ! -d $BACKUP_FORDER ] ;
        then
                mkdir $BACKUP_FORDER
		echo "echo > create backup forder"
        fi

        if [ ! -d $DEPLOY_FORDER ] ;
        then
                mkdir $DEPLOY_FORDER
		echo "echo > create deploy forder"
        fi

	sleep 2

        cd $DEPLOY_FORDER
	echo "echo > cd $DEPLOY_FORDER"

        sleep 2

        CURRENT_DEPLOY=$(ls | grep *.$EXTENSION | tail -n 1)
        echo "echo > CURRENT_DEPLOY => $CURRENT_DEPLOY"

        sleep 2

        if [ -z $CURRENT_DEPLOY ];
        then
                echo "echo > not existing current $EXTENSION"
        else
                TODAY=$(date "+%Y%m%d%H%M%S")
                echo "echo > existing $EXTENSION backup start"
                sudo cp -f $DEPLOY_FORDER/$CURRENT_DEPLOY $BACKUP_FORDER/$CURRENT_DEPLOY.$TODAY
				echo "echo > backup end"
				find $BACKUP_FORDER -ctime +$FILE_ARCHIVE_DAY -exec rm -f {} \;
        fi

        sleep 2

        cd $BUILD_FORDER
        echo "echo > cd $BUILD_FORDER"

	sleep 2

        NEW_DEPLOY=$(ls | grep *.$EXTENSION | tail -n 1)
        echo "echo > NEW_DEPLOY => $NEW_DEPLOY"

	sleep 2

        if [ -z $NEW_DEPLOY ];
        then
                echo "echo > not existing new jar"
        else
                cp -f $BUILD_FORDER/$NEW_DEPLOY $DEPLOY_FORDER/
                echo "echo > new $EXTENSION move to deploy forder"
	
	        sleep 2

		cd /$DEPLOY_FORDER
		echo "echo > cd $DEPLOY_FORDER"

		sleep 2
	
		PID=$(sudo /usr/sbin/lsof -t -i TCP:$PORT)
		echo "> PID => $PID"
		
		if [ -z $PID ]; 
		then
			echo "echo > application not running"
			sleep 1
			echo "echo > application run start"
			sleep 1
			rm -rf $DEPLOY_FORDER/$LOG_FILE_NAME
			/usr/bin/nohup java -jar $NEW_DEPLOY --spring.profiles.active=$SPRING_PROFILE > $DEPLOY_FORDER/$LOG_FILE_NAME 2>&1 &
			echo "> deploy and application run success"
		else
			echo "> kill -9 $PID"
			sudo kill -9 $PID
			sleep 1
			echo "echo > waiting 3"
			sleep 1
			echo "echo > waiting 2"
			sleep 1
			echo "echo > waiting 1"
			rm -rf $DEPLOY_FORDER/$LOG_FILE_NAME
			/usr/bin/nohup java -jar $NEW_DEPLOY --spring.profiles.active=$SPRING_PROFILE > $DEPLOY_FORDER/$LOG_FILE_NAME 2>&1 &
			echo "echo > kill and deploy success"
			echo "echo > deploy and log location > $DEPLOY_FORDER"	
		fi
		
		sleep 3
		sudo chown root:offline_was $DEPLOY_FORDER/$LOG_FILE_NAME
		sudo chmod 444 $DEPLOY_FORDER/$LOG_FILE_NAME
	fi
fi
