#!/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 file or directory in linux agent machine.
#
# ARGUMENT(S):
#
#  1) To delete the given file
#
#       ARGUMENT FORMAT: <file_to_be_deleted_in_linux_agent_machine>
#       EXAMPLE        : /home/user/old/deletefile

#           RETURN VALUE                  MEANING

#                0             File/ directory deleted sucessfully.
#                1             Error while deleting the file/ directory.
#                2             Invalid arguments.
#                3             System files deletion is prohibited. If needed, Kindly edit this script. and proceed.

# 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 no of arguments are valid
  if [ $# -ne 1 ]; then
    echo "Incorrect Usage : Arguments mismatch."
    echo "Refer ARGUMENT(S) section in the script."
    break
  fi

  errorCode=0
  sourcePath=$1
  omitDir=$(echo $sourcePath | sed -n '/^\.$/ p' | wc -l)

  #current directory will not be removed.
  if [ $omitDir -ne 0 ]; then
    echo "Cannot remove current working directory"
    break
  fi

  #convert relative path to absolute path
  sourcePath=$(readlink -f "$sourcePath")
  pwd=$(echo $PWD)
  IsSysFile=0

  if [ -e "$sourcePath" ]; then
    if [ "$sourcepath" = "$pwd" ]; then
      echo "you are trying to remove current working directory"
      break
    fi
    sourcePath=$(echo $sourcePath | sed 's/\/$//')

    # Edit this line. The folders in DontDel will not be removed.
    DontDel=(/ /bin /boot /cdrom /dev /etc /home /lib /lib32 /lib64 /media /mnt /opt /proc /root /run /sbin /snap /srv /sys /tmp /usr /var /initrd.img /initrd.img.old /vmlinuz /vmlinuz.old /boot/grub /usr/bin /usr/sbin /usr/lib /usr/share /usr/include)
    for folder in "${DontDel[@]}"; do
      if [ "$sourcePath" = "$folder" ]; then
        echo "System File detected"
        IsSysFile=1
        break
      fi
    done

  else
    echo "No such file or directory"
    exit
  fi

  if [ $IsSysFile -eq 1 ]; then
    echo "CAUTION:You are trying to remove System Files.This may affect your system"
    errorCode=3
    break
  fi

  #Removing the file or directory
  rm -r $sourcePath

  sourceName=$(echo $sourcePath | sed 's/\(.*\)\/\(.*\)/\2/')
  if [ $? -eq 0 ]; then
    echo "\"$sourceName\" file/directory deleting successfully"
  else
    echo "Error while deleting file/directory"
    errorCode=1
  fi

done
errorFunc() {
  return $errorCode
}
errorFunc
