#!/bin/bash

exec > /dev/null 2>&1

zabbix_server_ip="34.213.69.136"

timerange_check () {
 case "$1"
 in
 "day"  ) btime=`date --date="1 day ago" +%FT%T` && key=$1;;
 "week" ) btime=`date --date="1 week ago" +%FT%T` && key=$1;;
 "month") btime=`date --date="1 month ago" +%FT%T` && key=$1;;
 *      ) echo "Allowed values are 'day', 'week' and 'month'"; exit 1 ;;
 esac
}

#hostname_check () {
# if $1 =~ ^KPIReport_\w+\.\w+\.\w+\.[\w\s]+$; then
#    host_string=$1
# else
#    echo "Host string has invalid format" > %2
#    exit 1
# fi
#}

while getopts h:t:z: option
do
 case "${option}"
 in
 h) hostname=${OPTARG};;
 t) timerange_check ${OPTARG};;
 z) zabbix_server_ip=${OPTARG};;
 \?) echo "Wrong parameter."
     exit
     ;;
 esac
done

testname=${hostname//SMART_}
IFS='.' read -r -a params <<< "$testname"
etime=`date +%FT%T`

output=`python /opt/wk/skpi-rgen/bin/skpi-rgen --test_groups ${params[0]} --test_regions ${params[1]} --test_environments ${params[2]} --test_names "${params[3]}" --selection_btime $btime --selection_etime $etime | grep -oP "(?<=REPORT_URL\[)[^\[\]]+(?=\])"`
/usr/bin/zabbix_sender -z $zabbix_server_ip -s "$hostname" -k $key -o "$output"