#!/bin/bash
######################################################################
#
#  Name: boomIIDGET
#
#  Description: Searches for Indication ID(s) based on filter terms
#               inside active or closed indication list and output it.
#
#
#  Author: Solmsdorf (equensWorldline)
#  Version: 1.00
#  Date: 13.12.2023
#
#  Input parameter: $1: i=ac|cl
#                  [$2: h=<host> | a=<appl> | g=<group> | o=<object> | t=<text>]
#                  [$3: h=<host> | a=<appl> | g=<group> | o=<object> | t=<text>]
#                  [$4: h=<host> | a=<appl> | g=<group> | o=<object> | t=<text>]
#                  [$5: h=<host> | a=<appl> | g=<group> | o=<object> | t=<text>]
#                  [$6: h=<host> | a=<appl> | g=<group> | o=<object> | t=<text>]
#
#  Return: 0 = Success
#          0 = Warning (filtered closed Indication not found)
#          1 = Error (>>curl -k ${SRV_URL}:${SRV_PORT}/json/fullindi_list?search.value=ID-3-${id}<< failed (response ${stat})!)
#          2 = Error (>>curl -k ${SRV_URL}:${SRV_PORT}/json/fullindi_list?search.value=ID-3-${id}<< failed (size not available)!)
#
#
#  Note: requires boom user relating configuration inside boom_env_ssl.cnf
#
#  Filter possibilities (indication attr.):  Host Application Group Object Text
# 
#  History:
#
#     date    |name| reason
#  ----------------------------------------------------------------
#  13/12/2023 | ps | (1.00) Initial Release
#
######################################################################

NAME=$(basename $0)
PID=$$

CNFFIL="boom_env_ssl.cnf"

fil=${0}
fil_short=$(basename ${fil})
if [ `echo ${fil} | egrep "^\/" | wc -l` -eq 0 ]
then
# path not starting with "/"
  if [ `echo ${fil} | egrep "^\.\." | wc -l` -ge 1 ] || [ `echo ${fil} | egrep "\/" | wc -l` -ge 1 ]
  then
# path starting with ".."
    pd=$(realpath ${fil})
    pd=$(dirname ${pd})
    fil="${pd}/${fil_short}"
  else
# path not starting with ".."
    pd=$(pwd)
    fil="${pd}/${fil_short}"
  fi
fi
WORKDIR=$(dirname ${fil})

source "${WORKDIR}/${CNFFIL}"
decr="openssl base64 -d | openssl aes-256-cbc -d -salt -pbkdf2 -pass pass:${p}"
DEC="eval ${decr}"


SEP=";"
TMPFILE="${TMPDIR}/${NAME}_parse_indis.tmp"
OUTFILE="${OUTDIR}/${NAME}_indis.csv"
ITEMS=30
STAT_STR="active|closed"

USAGE="
Usage: ${NAME} i=ac|cl [h=<host> ...] [a=<appl> ...]  [g=<group> ...] [o=<object> ...] [t=<text> ...] 
Note: filter data can be combined as required and provide an "ADD" search operation for ${STAT_STR} Indications.
Note: CSV output is written to ${OUTFILE}.
Note: if no filter is given all available ${STAT_STR} indications are requested which may abort due to memory bottleneck in case of an existing huge amount!
"

user=$(id |awk -F"=" '{print $2}' |awk -F"(" '{print $2}' | awk -F")" '{print $1}')

function ShowT()
{
  local timstmp=$(date "+%d.%m.%Y %T")

   echo -e "${timstmp} ${1}: ${2}"
}


# INIT+++++++++++++++++++++++++++++++++++++++

#  Arguments?
if [ $# -lt 1 ]
then
  printf "${USAGE} \n"
  exit 0
fi

if [ -z "${TMPDIR}" ] || [ -z "${OUTDIR}" ]
then
  ShowT ERROR "(${PID}) [${user}] - var(s) >>TMPDIR|OUTDIR<< unfilled in config file ${CNFFIL}!"
  exit 9
fi

PARAM_SEP="="
search_str=""
dbg=0

params=( "$@" ) # get args
paramslength=${#params[@]}
## Process args
for item in "${params[@]}"
do
## check if PARAM_SEP is present
  if [ ! -z "${item}" ] && [ `echo "${item}" | grep "${PARAM_SEP}" >/dev/null; echo $?` -ne 0 ] 
  then
    if [ ! -z "${item}" ] && [[ ${item} =~ "h" ]] || [[ ${item} =~ "?" ]]
    then
      printf "${USAGE} \n"
      exit 0
    else
      continue
    fi
  fi

  param_key="${item%%$PARAM_SEP*}"
  param_val="${item#*$PARAM_SEP}"
## eliminate "" from param value
  param_val=$(echo "${param_val}" |sed 's/\"//g')

#echo "DBG: param_key=$param_key  param_val=$param_val"
  if [ ! -z "${param_key}" ] && [ ${param_key} == "h" ]
  then
    param_val=$(echo "${param_val}" | sed -r 's/\s/\%20/g')
    if [ -z "${search_str}" ]
    then
      search_str="search.value=Host-3-${param_val}"
    else
      search_str="${search_str}&search.value=Host-3-${param_val}"
    fi
  elif [ ! -z "${param_key}" ] && [ ${param_key} == "a" ]
  then
    param_val=$(echo "${param_val}" | sed -r 's/\s/\%20/g')
    if [ -z "${search_str}" ]
    then
      search_str="search.value=Application-3-${param_val}"
    else
      search_str="${search_str}&search.value=Application-3-${param_val}"
    fi
  elif [ ! -z "${param_key}" ] && [ ${param_key} == "g" ]
  then
    param_val=$(echo "${param_val}" | sed -r 's/\s/\%20/g')
    if [ -z "${search_str}" ]
    then
      search_str="search.value=Group-3-${param_val}"
    else
      search_str="${search_str}&search.value=Group-3-${param_val}"
    fi
  elif [ ! -z "${param_key}" ] && [ ${param_key} == "o" ]
  then
    param_val=$(echo "${param_val}" | sed -r 's/\s/\%20/g')
    if [ -z "${search_str}" ]
    then
      search_str="search.value=Object-3-${param_val}"
    else
      search_str="${search_str}&search.value=Object-3-${param_val}"
    fi
  elif [ ! -z "${param_key}" ] && [ ${param_key} == "t" ]
  then
    param_val=$(echo "${param_val}" | sed -r 's/\s/\%20/g')
    if [ -z "${search_str}" ]
    then
      search_str="search.value=Text-3-${param_val}"
    else
      search_str="${search_str}&search.value=Text-3-${param_val}"
    fi
  elif [ ! -z "${param_key}" ] && [ ${param_key} == "d" ]
  then
    dbg=${param_val}
  elif [ ! -z "${param_key}" ] && [ ${param_key} == "i" ]
  then
    mod=${param_val}
  else
    ShowT ERROR "(${PID}) [${user}] argument unknown!"
    exit 3
  fi
done
#echo "DBG: search_str=$search_str"

# def.
getstr="fullindi_list"

if [ -z "${mod}" ]
then
  mod=ac
  STAT_STR=active
  getstr="fullindi_list"
else
  if [[ ${mod} =~ "ac" ]]
  then
    mod=ac
    STAT_STR=active
    getstr="fullindi_list"
  elif [[ ${mod} =~ "cl" ]]
  then
    mod=cl
    STAT_STR=closed
    getstr="cl_fullindi_list"
  else
    mod=ac
    STAT_STR=active
    getstr="fullindi_list"
  fi
fi
#echo "DBG: mod=$mod  STAT_STR=$STAT_STR getstr=$getstr"

# MAIN++++++++++++++++++++++++++++++++++++++++++

# get boom server's state
res=$(curl -w %{http_code} -s -k ${SRV_URL}:${SRV_PORT}/${SRV_STATPAG})
stat=$(echo ${res##*Policy})
if [ ${stat} -ne 200 ]
then
  ShowT ERROR "(${PID}) [${user}] - calling >>curl -k ${SRV_URL}:${SRV_PORT}/${SRV_STATPAG}<< failed (response ${stat})!"
  exit 1
fi
active=$(echo "${res}" | grep "Active=" | awk -F"=" '{print $2}')
closed=$(echo "${res}" | grep "Closed=" | awk -F"=" '{print $2}')
if [ ${mod} == "ac" ]
then
  if [ ${active} -gt ${HIGHQUANT} ] 
  then
    ShowT WARNING "(${PID}) [${user}] - big amount of active Indications (${active}) - processing may get memory bottleneck!"
  else
    ShowT INFO "(${PID}) [${user}] - total ${STAT_STR} Indications: ${active} "
  fi
else
  if [ ${closed} -gt ${HIGHQUANT} ]
  then
    ShowT WARNING "(${PID}) [${user}] - big amount of active Indications (${closed}) - processing may get memory bottleneck!"
  else
    ShowT INFO "(${PID}) [${user}] - total ${STAT_STR} Indications: ${closed} "
  fi
fi


ShowT INFO "(${PID}) [${user}] - export ${STAT_STR} Indications filtered by >>${search_str}<< .. wait .."

if [ -z "${search_str}" ]
then
## Attention: requesting all active/closed indications!
  res=$(curl -w %{http_code} -s -k ${SRV_URL}:${SRV_PORT}/json/${getstr} -K- <<< "-u ${BOOM_USR}:$(echo ${Penc}|${DEC})" -o ${TMPFILE})
else
  res=$(curl -w %{http_code} -s -k ${SRV_URL}:${SRV_PORT}/json/${getstr}?${search_str} -K- <<< "-u ${BOOM_USR}:$(echo ${Penc}|${DEC})" -o ${TMPFILE})
fi
# check response code
stat=$(echo ${res##*\}})
if [ ${stat} -ne 200 ]
then
  ShowT ERROR "(${PID}) [${user}] - calling >>curl -k ${SRV_URL}:${SRV_PORT}/json/${getstr} ..<< failed (response ${stat})!"
  exit 1
fi


## expected:   "size": <not_zero>,
## eliminate new line of siz
siz=$(awk -F"size\":" '{printf "%s",$2}' ${TMPFILE} | sed -r 's/\s+//' | sed 's/,//')

if [ -z "${siz}" ]
then
  ShowT ERROR "(${PID}) [${user}] - calling >>curl -k ${SRV_URL}:${SRV_PORT}/json/${getstr} ..<< failed (size not available)!"
  exit 2   
fi

if [ ${siz} -eq 0 ]
then
    ShowT WARNING "(${PID}) [${user}] - filtered ${STAT_STR} Indication(s) not found"
    exit 0
fi
ShowT INFO "(${PID}) [${user}] - found ${siz} ${STAT_STR} Indications "


cnt=0
i=0
IFS=$'\n'

for line in `cat ${TMPFILE} | grep  "\"id\"" |awk -F": " '{print $2}'`
do 
  id=$(echo "${line}" |  sed 's/"//g' | sed 's/,//')
  echo ${id}
done

unset IFS
rm -f ${TMPFILE}

exit 0

