#!/bin/bash

# DISCLAIMER   :   It is recomended to test this script on a test machine.
#                  ManageEngine will not be responsible for any damage/loss
#                  to the data/setup based on the behavior of the script.
#
# DESCRIPTION  :   Script to delete the existing Cronjob in linux agent machines.
#
# ARGUMENT(S):
#      To know the full path of existing Cronjob kindly deploy the script "ListExistingCronJobsOnLinux.bash"
#
#      ARGUMENT FORMAT  : <full_path_of_script/application>
#      EXAMPLE          : /home/test/me_script.bash
#
#           RETURN VALUE          MEANING
#
#                0             Cronjob deleted successfully
#                1             Error while deleting Cronjob
#                2             Invalid arguments.
#
# NOTE :
#   To see the script output, Kindly enable the option Enable logging in Troubleshooting while deploying configuration.
errorCode=2

euid=$(id -u)
for i in 1; do

  #check root access
  if [ "$euid" -ne 0 ]; then
    echo "This script must be run as root"
    break
  fi

  #Check the number of arguments
  if [ $# -ne 1 ]; then
    echo "Incorrect Usage : Arguments mismatch."
    echo "Refer ARGUMENT(S) section in this script."
    break
  fi

  errorCode=0

  isPath=$(echo "$1" | sed -n '/^\// p' | wc -l)

  if [ "$isPath" -eq 0 ]; then
    fileName=$1
    runDir=$PWD
    cd ..
    fileDir=$PWD
    cd "$runDir"

    filePath=$(echo $fileDir"/"$fileName)

  else
    filePath=$1

  fi

  #Check the Job exist or not
  filePath=$(echo "$filePath" | sed 's/\//\\\//g')

  echo "FilePath: $filePath"

  isExist=$(crontab -l | sed -n '/\ '"$filePath"'$/p' | wc -l)

  if [ "$isExist" -eq 1 ]; then
    #remove the existing job
    crontab -l | sed '/\ '$filePath'$/ {
    d
  }' | crontab -

  else
    echo "No such Job for specified"
    break
  fi

  if [ $? -eq 0 ]; then
    echo "Cronjob deleted successfully"
  else
    echo "Error while deleting Cronjob"
    errorCode=1
  fi
done

errorFunc() {
  return ${errorCode}
}

errorFunc
