#!/bin/sh

# user check
USER=`whoami`
if [ "${USER}" != "ejobmgr" ];then
  echo "please execute this command as ejobmgr"
  exit 1
fi

# global.cof load
LANG=C;export LANG
SCRIPT_DIR=`dirname $0`
. ${SCRIPT_DIR}/../global.conf


REPOSITORY_JOBWRAPPER=$1
ENDPOINT=$2


if [ "${REPOSITORY_JOBWRAPPER}" = "" ];then
  echo "usage is following"
  echo "rm_jobwrapper <REPOSITORY>/<JOBWRAPPER>"
  exit 1
fi

REPOSITORY=`echo "${REPOSITORY_JOBWRAPPER}" | awk -F"/" '{print $1}'`
JOBWRAPPER=`echo "${REPOSITORY_JOBWRAPPER}" | awk -F"/" '{print $2}'`

if [ ! -d "${ROOT}/repository/${REPOSITORY}/${JOBWRAPPER}" -o "${JOBWRAPPER}" = "" ];then
  echo "ERROR no such jobwrapper"
  exit 1
fi

## jobwrapper input
echo "You will delete ${REPOSITORY}/${JOBWRAPPER} from all endpoints,is it OK?"
echo "If no problem please type \"yes\""
read ANSWER

if [ ! "${ANSWER}" = "yes" ];then
  echo "${REPOSITORY}/${JOBWRAPPER} is not deleted"
  exit 1
fi


while read RHOST
do
  ENDPOINT=`echo ${RHOST} | awk  -F":" '{print $1}'`

  if [ -d ${ROOT}/endpoints/${ENDPOINT}/repository/${REPOSITORY}/${JOBWRAPPER} ];then
    . ${ROOT}/endpoints/${ENDPOINT}/endpoint.conf
    ${ROOT}/bin/disable_jobwrapper ${REPOSITORY}/${JOBWRAPPER} ${ENDPOINT}
    ssh -o "ConnectTimeout 5" -p ${SSH_PORT} ${ENDPOINT} rm -rf ${USER_ROOT}/repository/${REPOSITORY}/${JOBWRAPPER}
    echo "rm -rf ${ROOT}/endpoints/${ENDPOINT}/repository/${REPOSITORY}/${JOBWRAPPER}"
    rm -rf ${ROOT}/endpoints/${ENDPOINT}/repository/${REPOSITORY}/${JOBWRAPPER}
  fi

done < ${ROOT}/map.conf

echo "rm -rf ${ROOT}/repository/${REPOSITORY}/${JOBWRAPPER}"
rm -rf ${ROOT}/repository/${REPOSITORY}/${JOBWRAPPER}

echo "-------------------------------------------------------------"
echo "${JOBWRAPPER} deleted succesfully. "
echo "-------------------------------------------------------------"

exit 0
