#!/bin/bash

## Example : VAR = url grafana_segment context_key context_value category_key category_value
##                  $url pdva plateform web context main_pages type smokeping
##					$url pdva plateform app context ... type smokeping

#URL_MAJ_PO_FOOT=$URL_MAIN_PARIS_OUVERTS"/football"
#URL_MAJ_PO_BASKET=$URL_MAIN_PARIS_OUVERTS"/basketball"
#URL_MAJ_PO_TENNIS=$URL_MAIN_PARIS_OUVERTS"/tennis"
#URL_MAJ_PO_RUGBY=$URL_MAIN_PARIS_OUVERTS"/rugby"

__NO_COMMIT=0
if [[ $__NO_COMMIT -eq 1 ]]; then echo "##### DONT FORGET TO RESET 'NO_COMMIT' to 0 ! #####";fi

function logging () {
	DATE=$(date)
	echo -e $DATE">\t"$1"\t${@:2}" >> $LOGPATH
	if [[ $OPT == 'debug' || $OPT2 == 'debug' ]]; then
		echo -e $DATE">\t"$1"\t${@:2}"
	fi
}

function influxDBCommit() { ## component #web #main_pages #label #value
	__component=$1
	__plateform_value=$2
	__context_value=$3
	__label=$4
	__value=$5

	__field=$(echo $__plateform_value'-'$__context_value'-'$__label | awk '{print tolower($0)}')
	# echo "$a" | awk '{print tolower($0)}'
	#field : web-main_pages-label-type

	TT_SEC=$(date --date="+40 seconds" +%s)
	TT_SEC_MIL=$(echo $TT_SEC'000000000')

	logging 'component='$__component', __field='$__field', __value='$__value', TT SEC MIL='$TT_SEC_MIL

	__influxEnv='prod'
	if [[ $__int_sufix == *"int"* ]]; then
		__influxEnv=${__int_sufix##*-}
	fi

	#echo "My Env: "$__influxEnv

	#/usr/bin/curl -i -XPOST 'http://192.168.250.41:8086/write?db='$__DATABASE --data-binary $__component','$__plateform_key'='$__plateform_value','$__context_key'='$__context_value',label='$__label' value='$__value' '$TT_SEC_MIL -o /dev/null -s
	#logging /usr/bin/curl -i -XPOST "'http://192.168.250.41:8086/write?db=$__DATABASE' --data-binary '$__component,country=FRA $__field=$__value $TT_SEC_MIL'" -o /dev/null -s
	#REQ=$( echo /usr/bin/curl -i -XPOST "'http://192.168.155.41:8086/write?db=$__DATABASE' --data-binary '$__component,country=FRA $__field=$__value $TT_SEC_MIL'" -o /dev/null -s )
	REQ=$( echo /usr/bin/curl -i -XPOST "'http://192.168.155.41:8086/write?db=$__DATABASE' --data-binary '$__component,env=$__influxEnv $__field=$__value $TT_SEC_MIL'" -o /dev/null -s )

	eval $REQ
	#echo "req="$REQ

	logging $REQ

	#/usr/bin/curl -i -XPOST 'http://192.168.250.41:8086/write?db=db_hermes_pspdva' --data-binary 'pdva_smokeping,mytag=1 web-main_pages-MAIN_HELP=0.555 1634056062000000000'
}

function bundle_checker () {
	## Bundle rate :
	# Uniquement sur le return code ?
	# ABP : Uniquement ABP
	# OFFRE : API Best
	# Account : --> Session (/1)
	#			--> Widgets (/4)
	# Live : Topmarker (/1)
	# Challenge : iOS/And (/2)

	# Bundles only works on return codes.
	# Bundles if check for return code bundle.expect and if not present considers 200 a OK and 400+ a KO 

	__bundle_label=$1
	__bundle_result=$2

	if [[ $__bundle_check -eq 1 ]]; then
		#context_value --> 'challenge_check'

		__specificReturnCode=$(cat $MY_PATH'/endpoints/bundle.expect' | grep $__bundle_label | awk '{print $2}')
		if [[ $__specificReturnCode == "" ]]; then
			#no codes
			#echo 'no specific codes for '$__bundle_label
			if [[ $__bundle_result -eq 200 ]]; then	
				bundle_score=$((bundle_score+1))
			fi
		else
			#echo $__bundle_label' code is "'$__specificReturnCode'"'
			if [[ $__bundle_result -eq $__specificReturnCode ]]; then
				bundle_score=$((bundle_score+1))
				echo "bundle_checker: we'd specific code request for ${__bundle_label}: ${__specificReturnCode}"
			fi
		fi

	#else
	#	echo "Bundle checker is disabled"
	fi
}

function postMan () {
	i=0;
	bundle_score=0
	for url in ${MAIN_LIST[@]}; do
		LABEL=${MAIN_LIST_LABELS[$i]}
		OPTION=${MAIN_LIST_OPTION[$i]}
		OPT_ARG=${MAIN_LIST_OPT_ARG[$i]}

		__genericOptionParameters=''

		case $OPTION in
			AUTH )
				if [[ $OPT_ARG == 'getHSToken' ]]; then
					#statements  -H "X-LVS-HSToken: ${hsToken}" -H "Content-Type: application/json"
					__genericOptionParameters=$(echo ' -H "X-LVS-HSToken: '${hsToken}'" -H "Content-Type: application/json"')
				fi
				;;

			DYNAMIC )
				if [[ $OPT_ARG == 'getToBasket' ]]; then
					url=$(echo ${url//__toBasket__/$toBasketID})
				elif [[ $OPT_ARG == 'getChallengePath' ]]; then
					url=$(echo ${url//__challengePath__/$challengePath})
				fi

				#__genericOptionParameters=$(echo $OPT_ARG)
				;;
			DYNAMIC_AUTH )
				#2020-05-15T10
				#https://www.enligne.parionssport.fdj.fr/lvs-api/ff/p240,p239,p227,p22877,p1100,p1200,p1250,p1300,p2200,p237,p22884,p238,p4011,p1800,p22878,p2100,p226,p1,p3700,p5000,p6012,p1201?originId=3&lineId=1&breakdownEventsIntoDays=true&startTime
				#=2022-10-26T00:00:00 02:00&endTime=2022-10-27T00:00:00 02:00&pageIndex=0&eventsPerPage=50&eType=G&showPromotions=true
				if [[ $OPT_ARG == 'getHSToken' ]]; then
					url=$(echo ${url//__GMT_OFFSET__/$gmtOffset})
					url=$(echo ${url//__START_DATE__/$startDate})					
					url=$(echo ${url//__END_DATE__/$endDate})
					__genericOptionParameters=$(echo ' -H "X-LVS-HSToken: '$hsToken'" -H "Content-Type: application/json"')
				fi
				;;

		esac

		case $category_value in
			smokeping )
				CALL="/usr/bin/curl -Ss -o /dev/null -w %{time_starttransfer} ${resolvPRD} ${url} ${__genericOptionParameters}"
				RESPONSE=$(eval $CALL)
				
				#curl -s -S -I --resolve www.enligne.parionssport.fdj.fr:443:8.8.8.8 --verbose https://www.enligne.parionssport.fdj.fr
				#RESPONSE=$(/usr/bin/curl -S -I --resolve "'${url}':443:8.8.8.8" $url -s -o /dev/null -w %{time_starttransfer})
				logging $LABEL' --> '$url': '$RESPONSE' sec'

				;;
			returncode )
				CALL="/usr/bin/curl -Ss -o /dev/null -w %{http_code} ${resolvPRD} ${url} ${__genericOptionParameters}"
				#echo '--->> Call: '$CALL
				#RESPONSE=$(/usr/bin/curl -S -I --resolve "'${url}':443:8.8.8.8" $url -s -o /dev/null -w %{http_code})
				#RESPONSE=$(/usr/bin/curl -Ss ${resolvPRD} ${url} -H "X-LVS-HSToken: ${hsToken}" -H "Content-Type: application/json" -o /dev/null -w %{http_code})
				RESPONSE=$(eval $CALL)
				logging $LABEL' --> '$url': '$RESPONSE

				bundle_checker $LABEL $RESPONSE

				;;
			queryvalue )
				logging "url:" $url
				logging "OPTION" $OPTION
				logging "OPT_ARG" $OPT_ARG
                RESPONSE=$(/usr/bin/curl $url | $OPTION "${OPT_ARG}")
				#echo /usr/bin/curl -S -I --resolve "'${url}':443:8.8.8.8" $url -s -o /dev/null | ${OPTION} ${OPT_ARG}
				logging $LABEL' --> '$url': '$RESPONSE

				;;
			* )
				echo "Category not found"
				exit 1;
				;;
		esac

		#influxDBCommit $__Context'_'$category_value $plateform_key $plateform_value $context_key $context_value $LABEL $RESPONSE
		__component=$(echo $__Context'_'$category_value)

		echo "LABEL: "$LABEL" | url="$url" | GOP="$__genericOptionParameters" | RESP: "$RESPONSE

		
		##TO DECOM##
		if [[ $__NO_COMMIT -eq 0 ]]; then
			influxDBCommit $__component $plateform_value $context_value $LABEL $RESPONSE
		else
			echo "LABEL: "$LABEL" | url="$url" | GOP="$__genericOptionParameters" | RESP: "$RESPONSE
		fi


		i=$((i+1))

	done

	if [[ $__bundle_check -eq 1 ]]; then
		#plateform_value=$1	# web|app / bundle
		#context_value=$2	# major_sports|<...>|challenge_check
		#category_value=$3	# test category: smokeping|errorcode
		__bundleSpecComponent=$(echo $__Context'_bundle') #$__int_sufix)
		__bndl_ctxValue=${context_value%%_*}


		echo "Bundle_score: "$bundle_score"/"$i
		if [[ $__NO_COMMIT -eq 0 ]]; then
			influxDBCommit $__bundleSpecComponent $plateform_value $context_value $__bndl_ctxValue $bundle_score
		else
			echo "Bundle_score: "$bundle_score"/"$i
			echo "commit : "$__bundleSpecComponent" / "$plateform_value" / "$context_value" / "$__bndl_ctxValue" : "$bundle_score
		fi

		#				challenge_check_bundle	bundle 	challenge_chec 	BNDL_context_value-->trimmed $bundle_score 
	fi
}

function getContext () {
	__bundle_check=0

	MY_PATH="`dirname \"$0\"`"
	MY_PATH="`( cd \"$MY_PATH\" && pwd )`"
	SUB_PATH=${MY_PATH##*/}

	###			###
	# Switch Case #
	###			###
	if [[ $plateform_value == *"bundle"* && $category_value == 'returncode' ]]; then __bundle_check=1;	fi # 	echo "Bundle check....";	fi
	if [[ $OPT == *"int"* ]]; then
		__int_sufix=$(echo '-'$OPT)
	else
		resolvPRD="--resolve \"'www.enligne.parionssport.fdj.fr':443:8.8.8.8\""
	fi

	###			###
	# DB Handling #
	###			###
	case $SUB_PATH in
		pdva)
			__Context='pdva' ; __DATABASE='db_hermes_pspdva' ;;
		psel)
			__Context='psel' ; __DATABASE='db_hermes_psel' ;;
		pscp)
			__Context='pscp' ; __DATABASE='db_hermes_pscp' ;; ## __DATABASE='db_hermes_pscp'$__int_sufix 
		*)
			__Context='n/a' ; __DATABASE='' 
			echo "No context found. Bye"
			exit 1;;
	esac

	#echo 'db: '$__DATABASE
	#exit 1
}

#### Needed Args
# DB + all args required within idbCommit --> OK
# pdva is known (static in script (dirname)) --> OK @context
# plateform_key is static --> OK
# plateform value is REQUIRED --> Asked
# context is REQUIRED (main_pages) --> Ok & Asked
# category is static
# categopry value is REQUIRED (type)

### DBS :
# db_hermes_pspdva
# db_hermes_psel
# db_hermes_pscp

if [[ $1 == '' ]] || [[ $2 == '' ]] || [[ $3 == '' ]]; then
	echo "Error: Incorrect parameters. Usage: plateform_value(web|app) context_value(main_pages,major_sports) category_value(smokeping|errorcode)"
	exit 1;
fi

__int_sufix=''
resolvPRD=''

plateform_key="plateform"
context_key="context"
category_key="type"

# <platform>_<context>.list
plateform_value=$1	# web|app / bundle
context_value=$2	# major_sports|<...>|challenge_check
category_value=$3	# test category: smokeping|errorcode
OPT=$4
OPT2=$5


#echo "platform value: "$plateform_value
#echo "context_value: "$context_value
#echo "category_value : "$category_value
#echo "OPT : "$OPT
#echo "OPT2 : "$OPT2


getContext

LOGPATH='/root/logs/'$category_value'_'$__Context'_'$plateform_value'_'$context_value$__int_sufix'.log'
logging $MY_PATH' --> Context: '$__Context' ['$__DATABASE']'


# Build the list file path.
# Current path + "/endpoints/" + plateform_key + context + '.list'

LIST_FILEPATH=$MY_PATH'/endpoints/'$plateform_value'_'$context_value$__int_sufix'.list'
echo -ne 'File: "'$LIST_FILEPATH'" '
if [ -f "$LIST_FILEPATH" ]; then
	echo 'exists'
else
	echo 'not found!'
	exit 1;
fi

MAIN_LIST=($(cat $LIST_FILEPATH | awk '{print $2}'))
MAIN_LIST_LABELS=($(cat $LIST_FILEPATH | awk '{print $1}'))
MAIN_LIST_OPTION=($(cat $LIST_FILEPATH | awk '$3==""{print "noOptions"};$3!=""{print $3}'))
MAIN_LIST_OPT_ARG=($(cat $LIST_FILEPATH | awk '$4==""{print "noOptArgs"};$4!=""{print $4}'))

#MAIN_LIST_OPTION=($(cat $LIST_FILEPATH -e | awk '{print $3}'))
#MAIN_LIST_OPT_ARG=($(cat $LIST_FILEPATH -e | awk '{print $4}'))

###################
## Global Values ##
###################
hsToken=$(cat "/tmp/_psel_hsToken${__int_sufix}.token")
toBasketID=$(cat "/tmp/_psel_toBasket${__int_sufix}")
challengePath=$(cat "/tmp/_psel_challengePath${__int_sufix}")


# url=$(echo ${url//__GMT_OFFSET__/$gmtOffset}) ## GET 0100
# url=$(echo ${url//__START_DATE__/$startDate}) ## GET DateNow 					
# url=$(echo ${url//__END_DATE__/$endDate}) 	## GET Date End (Now +1 d)
#https://www.enligne.parionssport.fdj.fr/lvs-api/ff/p240,p239,p227,p22877,p1100,p1200,p1250,p1300,p2200,p237,p22884,p238,p4011,p1800,p22878,p2100,p226,p1,p3700,p5000,p6012,p1201?originId=3&lineId=1&breakdownEventsIntoDays=true&startTime
#=2022-10-26T00:00:00 02:00&endTime=2022-10-27T00:00:00 02:00&pageIndex=0&eventsPerPage=50&eType=G&showPromotions=true
#https://www.enligne.parionssport.fdj.fr/lvs-api/ff/p240,p239,p227,p22877,p1100,p1200,p1250,p1300,p2200,p237,p22884,p238,p4011,p1800,p22878,p2100,p226,p1,p3700,p5000,p6012,p1201?originId=3&lineId=1&breakdownEventsIntoDays=true&startTime
#=2022-10-25T00:00:00+02:00&endTime=2022-10-26T00:00:00+02:00&pageIndex=0&eventsPerPage=50&eType=G&showPromotions=true

__nowDate=$(date '+%Y-%m-%d')
__tomorrowDate=$(date '+%Y-%m-%d' -d 'tomorrow')
startDate=$(echo $__nowDate'T00')
endDate=$(echo $__tomorrowDate'T00')
gmtOffset=$(cat /tmp/gmtOffset)

postMan

exit 1;
