#!/bin/bash
######################################################################
#
#  Name: boomINDIGET
#
#  Description: gets indication details via boom server REST API. 
#               Provide semicolon separated output of 32 indication attributes.
#               Indication ID will be searched at first as active and if
#               not found as closed.
#
#
#  Author: Solmsdorf (equensWorldline)
#  Version: 1.00
#  Date: 13.12.2023
#
#  Input parameter: <indication_id>
#
#  Return: 0 = Success
#          0 = Warning (Indication with ID $id does not exist)
#          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
#
#  Indication Attributes Layout (example call /json/fullindi.lst):
#      1       "id": "41e12240-06ab-4328-906a-a4b89a6e3584",
#      2       "severity": 4,
#      3       "duplicates": 0,
#      4       "time": 1702375028463,
#      5       "host": "u999imogw001d",
#      6       "application": "a",
#      7       "group": "",
#      8       "object": "o",
#      9       "text": "mit Komma, PSO",
#     10       "agent": "u999imogw001d",
#     11       "stime": 1702375035245,
#     12       "agentid": "21acacdf-6daa-44d1-8dbd-bd330c46bc11",
#     13       "typea": 0,
#     14       "typek": 0,
#     15       "dd": true,
#     16       "ddko": false,
#     17       "state": "-",
#     18       "tfa": 0,
#     19       "vfa": 0.0,
#     20       "monitor": "",
#     21       "value": -1.0,
#     22       "ftime": 1702375028463,
#     23       "policysource": "Message:TSTindi:acfb3d38-455d-42d3-a100-3bcbe0875        d8d",
#     24       "owner": "",
#     25       "key": "u999imogw001d:u999imogw001d:a::o:major",
#     26       "closemask": "u999imogw001d:u999imogw001d:a::o:\u003c*\u003e",
#     27       "oaction": "",
#     28       "aaction": "",
#     29       "aactionnode": "",
#     30       "aactionflag": false,
#     31       "adviceid": "36081df7-5c77-4e5c-a1c2-e7564f8f40c8",
#     32       "advice": "Achtung Kommatest",
#     33       "instruction_url": "",
#     34       "annoflag": true,
#     35       "annotations": [
#     36         {
#     37 annotim_: 1702376711329,
#     38           "flag": "OMN",
#     39 annotxt_: "pso Annotationtest PSO"
#     40         },
#     41         {
#     42 annotim_: 1702378029276,
#     43           "flag": "OMN",
#     44 annotxt_: "pso next Annotation 2"
#     45         }
#     46       ],
#     47       "cas": [
#     48         {
#     49           "ca1": "cust1\u003dkommatest-1"
#     50         },
#     51         {
#     52           "ca5": "cust5\u003dkommatest-5"
#     53         }
#     54       ]
#     55     }
#     56   ],
#     57   "draw": 0
#
#  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_indi.tmp"

USAGE="
Usage: ${NAME} <indication-id>
Note: Indication ID will be searched at first as >>active<< and if not found as >>closed<<.
"

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+++++++++++++++++++++++++++++++++++++++

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

id=${1}

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

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

res=$(curl -w %{http_code} -s -k ${SRV_URL}:${SRV_PORT}/json/fullindi_list?search.value=ID-3-${id} -K- <<< "-u ${BOOM_USR}:$(echo ${Penc}|${DEC})" -o ${TMPFILE})
# check response code
stat=$(echo ${res##*\}})
if [ ${stat} -ne 200 ]
then
  ShowT ERROR "(${PID}) [${user}] - calling >>curl -k ${SRV_URL}:${SRV_PORT}/json/fullindi_list?search.value=ID-3-${id}<< failed (response ${stat})!"
  exit 1
fi

## expected:   "size": 1,
## 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/fullindi_list?search.value=ID-3-${id}<< failed (size not available)!"
  exit 2   
fi

# try get_closed_indication
if [ ${siz} -eq 0 ]
then
  res=$(curl -w %{http_code} -s -k ${SRV_URL}:${SRV_PORT}/json/cl_fullindi_list?search.value=ID-3-${id} -K- <<< "-u ${BOOM_USR}:$(echo ${Penc}|${DEC})" -o ${TMPFILE})
  stat=$(echo ${res##*\}})
  if [ ${stat} -ne 200 ]
  then
    ShowT ERROR "(${PID}) [${user}] - calling >>curl -k ${SRV_URL}:${SRV_PORT}/json/cl_fullindi_list?search.value=ID-3-${id}<< failed (response ${stat})!"
    exit 1
  fi
## eliminate new line of siz
  siz=$(awk -F"size\":" '{printf "%s",$2}' ${TMPFILE} | sed -r 's/\s+//' | sed 's/,//')
  if [ -z "${siz}" ] || [ ${siz} -ne 1 ]
  then
    ShowT WARNING "(${PID}) [${user}] - Indication with ID $id does not exist"
    exit 0
  else
    printf "Indication with ID $id exists as >>CLOSED<< .. "
  fi
else
  printf "Indication with ID $id exists as >>ACTIVE<< .. "
fi

## perparatory actions inside TMPFILE: setting unique anchors
## replace in-place "time" and "text" inside annotations section (10 x spaces)
## by "annotim_" and "annotxt_"
sed -r -i -e 's/^\s{10}\"time\"/annotim_/' -e 's/^\s{10}\"text\"/annotxt_/' -e 's/\\n/ /g' ${TMPFILE}

declare -a la
cnt=0
i=0
IFS=$'\n'
for line in `cat ${TMPFILE} | egrep "(\"text\"|\"severity\"|\"id\"|\"application\"|\"group\"|\"host\"|\"agent\"|\"typek\"|\"typea\"|\"object\"|\"key\"|\"closemask\"|\"aaction\"|\"aactionnode\"|\"oaction\"|\"policysource\"|\"state\"|\"duplicates\"|\"ftime\"|\"time\"|\"stime\"|\"value\"|\"vfa\"|\"tfa\"|\"ddko\"|\"agentid\"|\"owner\"|\"dd\"|\"monitor\"|\"advice\")" |awk -F": " '{print $2}'`
do 
  ((cnt++))
## replace spec. CHARs
  lin=$(echo ${line} |sed 's/"//g' | sed 's/,$//')
  echo ${lin} | grep -q -e ";" -e "\u0027" -e "\\" && { 
##  enclose with double quotes due to spec. CHARs or occurence of ";"?
##  yes, because of boom's automatism (\ ==> \\  ' ==> \u0027)
## sed "s/\\u0027/'/g" ==> \' (extra "\" added after subsitute)
    lin=$(echo ${lin} | sed -r 's/\\{2}/\\/g' | sed "s/\\u0027/'/g" |  sed -r 's/\\'\''/'\''/g')
    lin="\"${lin}\""
}

## store line into array (providing adjusted attribute sequence for output)
    la[${cnt}]=${lin}

done
unset IFS


# CAs
((cnt++))
## printf "%s",$2: eliminate new line (cas without \n)
cas=$(awk -v m=": \"" '/cas/,/\]/ {if ($0 ~m){print $0}}' ${TMPFILE} |awk -F":" '{printf "%s",$2}' |sed 's/"//g' |sed 's/\\u003d/=/g')
ca_cnt=$cnt
la[${ca_cnt}]=${cas}

# Annotations
((cnt++))
## printf "%s",$2: eliminate new line (annos without \n)
annos=$(awk -v m="_: " '/annotations/,/\]/ {if ($0 ~m){print $0}}' ${TMPFILE} | awk -F"_:" '{printf "%s",$2}' | sed 's/,/ /g' |sed 's/"//g')
anno_cnt=$cnt
##  enclose with double quotes due to spec. CHARs or occurence of ";"?
echo ${annos} | grep -q -e ";" -e "\u0027" -e "\\" && { 
##  yes, because of boom's automatism (\ ==> \\  ' ==> \u0027)
## sed "s/\\u0027/'/g" ==> \' (extra "\" added after subsitute)
  annos=$(echo ${annos} | sed -r 's/\\{2}/\\/g' | sed "s/\\u0027/'/g" |  sed -r 's/\\'\''/'\''/g')
  annos="\"${annos}\""
}
la[${anno_cnt}]=${annos}

# Output: Header and attributes line
printf "providing ${cnt} items for next 2 lines (Header, Attributes): \n"

echo "INDICATION TEXT${SEP}SEVERITY${SEP}UUID${SEP}APPLICATION${SEP}GROUP${SEP}HOST${SEP}AGENT HOST${SEP}KPI METRIC${SEP}AVAILABILITY METRIC${SEP}OBJECT${SEP}KEY${SEP}CLOSE MASK${SEP}AUTO-ACTION${SEP}AUTO-ACTION HOST${SEP}OP-ACTION${SEP}SOURCE${SEP}STATE${SEP}DUPLICATES${SEP}FIRST SUBMIT${SEP}LAST DUPLICATE${SEP}SERVER RECEIVED${SEP}VALUE${SEP}END VALUE${SEP}ALERT FINISHED${SEP}DEDUPLICATION KEYONLY${SEP}AGENTID${SEP}OWNER${SEP}ADVICE${SEP}CUSTOM ATTRIBUTES${SEP}ANNOTATIONS" 

# epoch without milliseconds
epoch=$(echo ${la[4]} |cut -c -10)
la[4]=$(date -d @$epoch +"%Y-%m-%d %H:%M:%S")

epoch=$(echo ${la[11]} |cut -c -10)
la[11]=$(date -d @$epoch +"%Y-%m-%d %H:%M:%S")

epoch=$(echo ${la[22]} |cut -c -10)
la[22]=$(date -d @$epoch +"%Y-%m-%d %H:%M:%S")

echo "${la[9]}${SEP}${la[2]}${SEP}${la[1]}${SEP}${la[6]}${SEP}${la[7]}${SEP}${la[5]}${SEP}${la[10]}${SEP}${la[14]}${SEP}${la[13]}${SEP}${la[8]}${SEP}${la[25]}${SEP}${la[26]}${SEP}${la[28]}${SEP}${la[29]}${SEP}${la[27]}${SEP}${la[23]}${SEP}${la[17]}${SEP}${la[3]}${SEP}${la[22]}${SEP}${la[4]}${SEP}${la[11]}${SEP}${la[21]}${SEP}${la[19]}${SEP}${la[18]}${SEP}${la[16]}${SEP}${la[12]}${SEP}${la[24]}${SEP}${la[30]}${SEP}${la[${ca_cnt}]}${SEP}${la[${anno_cnt}]}" 

unset la
rm -f ${TMPFILE}
exit 0

