#!/bin/bash

serviceLocation=$1
serviceName="techmine"
backupLocation="./serviceBackup"
latestServiceLocation="./latestService"

function moveAndStart()
{
    #echo "Sleeping 15 seconds"
    #sleep 15
    echo "checking if active"
    service=$(systemctl is-active $serviceName)
    if [ "$service" = "active" ]; then
        echo "checking latest service"
        if [ -d $latestServiceLocation ]; then
            echo "moving"
            mv $serviceLocation $backupLocation
            mv $latestServiceLocation $serviceLocation
            chmod -R 777 $serviceLocation
            #echo "Starting"
            #systemctl restart $serviceName
            #echo "Started"
            #service=$(systemctl is-active $serviceName)
            #if [ "$service" != "active" ]; then
            #    echo "Restoring"
            #    if [ -d $backupLocation ]; then
            #        mv $serviceLocation $latestServiceLocation
            #        mv $backupLocation $serviceLocation
            #        systemctl start $serviceName
            #    else
            #        systemctl start $serviceName
            #    fi
            #fi
            echo "Exiting"
        fi

    else
        echo "Could not stop service"
    fi
}
#trap moveAndStart 1 2 3 13 15

service=$(systemctl is-active $serviceName)
if [ -d $backupLocation ]; then
    rm -rf $backupLocation
fi
if [ "$service" = "active" ]; then
    #echo "Stopping service"
    #systemctl stop $serviceName || /bin/true
    #echo "Stopped"
    moveAndStart
else
    echo "The Service Is Not Running"
fi
