#!/bin/bash
# this script to execute LSF command
server=""
token=""
user=""
if [ -f "${HOME}/.pacpass" ]; then
  token=`cat "${HOME}/.pacpass"`
else
  echo "You are not logged on to IBM Spectrum LSF Application Center. Use the paclogon command to log on."
  exit 0
fi
if [ -f "${HOME}/LSFClient/user" ]; then
  user=`cat "${HOME}/LSFClient/user"`
else
  echo "You are not logged on to IBM Spectrum LSF Application Center. Use the paclogon command to log on."
  exit 0
fi
if [ -f "${HOME}/LSFClient/server" ]; then
  server=`cat "${HOME}/LSFClient/server"`
else
  echo "You are not logged on to IBM Spectrum LSF Application Center. Use the paclogon command to log on."
  exit 0
fi
mycmd="$0"
mycmd=$(basename $mycmd .sh)
for arg in "$@"; do
  arg="${arg//\</0x3c}"
  arg="${arg//\=/0x3d}"
  arg="${arg//\>/0x3e}"
  arg="${arg//\(/0x28}"
  arg="${arg//\)/0x29}"
  if [ "${arg:0:1}" != "-" ]; then
    mycmd="${mycmd} \"${arg}\""
  else
    mycmd="${mycmd} ${arg}"
  fi
done
#echo "mymcd=${mycmd}"

#Invoke web service by curl - format: exitCode～stdout
if [ "${token:0:6}" = "Bearer" ]; then
    content=$(curl -s --cacert "${0%/*}/cacert.pem" -H "Content-Type:multipart/form-data" -H "Auth-User: ${user}" -H "Authorization: ${token}" -X POST -F command="${mycmd}" "${server}/ws/scripts/execute")
else
    content=$(curl -s --cacert "${0%/*}/cacert.pem" -H "Content-Type:multipart/form-data" -H "Cookie: platform_token=${token//&quot;/#quote#}" -X POST -F command="${mycmd}" "${server}/ws/scripts/execute")
fi
EXITCODE_SEPARATE_CHAR="~"
exitCode=${content%%${EXITCODE_SEPARATE_CHAR}*}
output=${content#*${EXITCODE_SEPARATE_CHAR}}
if [ "$exitCode" == "$content" ]; then
	echo -e "${content}"
else
	echo -e "${output}"
	exit ${exitCode}
fi 
