#!/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
if [ -z "$1" -o -z "$2" ]; then 
  echo "Failed to register notification. Invalid regnotify options."
  echo "regnotify Usage:"
  echo -e ""
  echo "regnotify job_ID status [status...]"
  echo -e ""
  echo "Valid status values:"
  echo "- start"
  echo "- end"
  echo "- fail"
  echo "- suspend"
  exit 0
fi

flag="false"
args="{Policy:{via_mobile:true"
for arg in "$@"; do
  if [ "${arg}" = "start" ]; then
    args="${args},job_start:true"
    flag="true"
  fi
  if [ "${arg}" = "end" ]; then
    args="${args},job_end:true"
    flag="true"
  fi
  if [ "${arg}" = "fail" ]; then
    args="${args},job_fail:true"
    flag="true"
  fi
  if [ "${arg}" = "suspend" ]; then
    args="${args},job_suspend:true"
    flag="true"
  fi
done

if [ "${flag}" = "false" ]; then
  echo "Failed to register notification. The specified job state is not valid. Valid values are: start, end, fail, suspend."
  exit 0
fi
args="${args},via_desktop:true}}"
if [ "${token:0:6}" = "Bearer" ]; then
	curl --cacert "${0%/*}/cacert.pem" -H "Content-Type: application/json" -H "Auth-User: ${user}" -H "Authorization: ${token}" -X POST -d "${args}" "${server}/ws/notifications/$1"
else
	curl --cacert "${0%/*}/cacert.pem" -H "Content-Type: application/json" -H "Cookie: platform_token=${token//&quot;/#quote#}" -X POST -d "${args}" "${server}/ws/notifications/$1"
fi
echo -e ""
