#!/bin/sh
# Copyright (C) 2022 iopsys Software Solutions AB
# Author: AMIN Ben Romdhane <amin.benromdhane@iopsys.eu>

. /usr/share/libubox/jshn.sh
. /usr/share/bbfdm/scripts/bbf_api

udpecho_list() {
	json_add_object "udpecho"
	json_add_string "host" "str"
	json_add_string "port" "str"
	json_add_string "iface" "str"
	json_add_string "ip_proto" "str"
	json_add_string "nbr_of_rep" "str"
	json_add_string "timeout" "str"
	json_add_string "data_size" "str"
	json_add_string "dscp" "str"
	json_add_string "inter_trans_time" "str"
	json_add_string "proto" "str"
	json_add_string "cancel" "str"
	json_close_object
}

udpecho_error() {
	json_init
	json_add_string "Status" "$1"
	json_add_string "IPAddressUsed" ""
	json_add_int "SuccessCount" "0"
	json_add_int "FailureCount" "$2"
	json_add_int "MinimumResponseTime" "9999"
	json_add_int "AverageResponseTime" "0"
	json_add_int "MaximumResponseTime" "0"
	json_dump

	# Store data in dmmap_diagnostics for both protocols (cwmp/usp)
	[ "$3" = "both_proto" ] && {
		$UCI_SET_BBF_DMMAP dmmap_diagnostics.udpechodiag.DiagnosticState="$1"
		$UCI_SET_BBF_DMMAP dmmap_diagnostics.udpechodiag.SuccessCount=0
		$UCI_SET_BBF_DMMAP dmmap_diagnostics.udpechodiag.FailureCount="$2"
		$UCI_SET_BBF_DMMAP dmmap_diagnostics.udpechodiag.MinimumResponseTime=9999
		$UCI_SET_BBF_DMMAP dmmap_diagnostics.udpechodiag.AverageResponseTime=0
		$UCI_SET_BBF_DMMAP dmmap_diagnostics.udpechodiag.MaximumResponseTime=0
		$UCI_COMMIT_BBF_DMMAP
	}
}

udpecho_launch() {
	input="$1"

	json_load "${input}"
	
	json_get_var host host
	json_get_var port port
	json_get_var iface iface
	json_get_var ip_proto ip_proto
	json_get_var nbr_of_rep nbr_of_rep
	json_get_var timeout timeout
	json_get_var dsize data_size
	json_get_var dscp dscp
	json_get_var inter_time inter_trans_time
	json_get_var proto proto
	json_get_var cancel cancel

	[ "${proto}" = "both_proto" ] && {
		old_pid=$(cat /tmp/udpecho_pid)

		[ -n "${old_pid}" ] && {
			cmd=$(cat /proc/"${old_pid}"/cmdline)
		}

		if [[ "${cmd}" = *udpecho* ]]; then
			kill -9 "${old_pid}"
		fi

		if [ "${cancel}" -eq "1" ]; then
			$UCI_SET_BBF_DMMAP dmmap_diagnostics.udpechodiag.DiagnosticState="None"
			$UCI_SET_BBF_DMMAP dmmap_diagnostics.udpechodiag.SuccessCount="0"
			$UCI_SET_BBF_DMMAP dmmap_diagnostics.udpechodiag.FailureCount="0"
			$UCI_SET_BBF_DMMAP dmmap_diagnostics.udpechodiag.MinimumResponseTime="9999"
			$UCI_SET_BBF_DMMAP dmmap_diagnostics.udpechodiag.AverageResponseTime="0"
			$UCI_SET_BBF_DMMAP dmmap_diagnostics.udpechodiag.MaximumResponseTime="0"
			$UCI_SET_BBF_DMMAP dmmap_diagnostics.udpechodiag.IPAddressUsed=""
			$UCI_COMMIT_BBF_DMMAP

			json_init
			json_add_string "Status" "None"
			json_add_string "IPAddressUsed" ""
			json_add_int "SuccessCount" "0"
			json_add_int "FailureCount" "0"
			json_add_int "MinimumResponseTime" "9999"
			json_add_int "AverageResponseTime" "0"
			json_add_int "MaximumResponseTime" "0"
			json_dump

			return
		else
			echo $$ > /tmp/udpecho_pid
			$UCI_SET_BBF_DMMAP dmmap_diagnostics.udpechodiag.DiagnosticState="Requested_running"
			$UCI_COMMIT_BBF_DMMAP
		fi
	}

	# Fail if host is empty
	[ -z "${host}" ] && {
		udpecho_error "Error_Internal" "${nbr_of_rep}" "${proto}"
		return
	}

	if [ -n "${iface}" ]; then
		device=$(ifstatus "${iface}" | jsonfilter -e '@.l3_device')

		# If no device was found, return error
		[ -z "${device}" ] && {
			udpecho_error "Error_NoRouteToHost" "${nbr_of_rep}" "${proto}"
			return
		}
	else
		device=""
	fi

	# Assign default value
	[ -z "${nbr_of_rep}" ] && nbr_of_rep=1
	[ -z "${port}" ] && port=7
	[ -z "${dsize}" ] && dsize=24
	[ -z "${dscp}" ] && dscp=0
	ip_addr_used=$(get_ip_addr_used "${host}" "${ip_proto}" "${iface}")
	if [ "$ip_proto" = "IPv4" ]; then ip_proto="--protocol 4"; elif [ "$ip_proto" = "IPv6" ]; then ip_proto="--protocol 6"; else ip_proto=""; fi
	[ -z "${timeout}" ] && timeout=1 || timeout=$((timeout/1000))
	[ -z "${inter_time}" ] && inter_time=1 || inter_time=$((inter_time/1000))
	#tos=$((dscp<<2)) Not supported as of now in udpechoclientd

	micros=1000
	success_count=0
	avg_time_sum=0
	min=9999999
	max=0
	i=0

	while [ $i -lt "$nbr_of_rep" ]; do
		i=$((i+1))

		res=$(udpechoclientd -c 1 -t "$timeout" --host "$host" --data-length "$dsize" --port "$port" "$ip_proto" -i "$device" 2>&1)

		ba=$(echo "$res" | grep "Can't Resolve Host Name")
		[ -n "$ba" ] && {
			udpecho_error "Error_CannotResolveHostName" "${nbr_of_rep}" "${proto}"
			return
		}

		ba=$(echo "$res" | grep "RCVD")
		[[ -z "$ba" && $((nbr_of_rep-i)) == 0 ]] && {
			udpecho_error "Complete" "${nbr_of_rep}" "${proto}"
			return
		}

		times=$(echo "$res" | grep "rtt")
		[ -z "$times" ] && continue

		sc1=$(echo "$res" | grep "Rcvd" | awk -F': ' '{print $3}' | awk -F'(' '{ print $1 }')
		[ "$sc1" != 0 ] && sc1=1 || sc1=0

		success_count=$((success_count+sc1))
		max_time=$(echo "$times" | awk -F': ' '{ print $2 }' | awk -F'ms' '{ print $1 }')
		min_time=$(echo "$times" | awk -F': ' '{ print $3 }' | awk -F'ms' '{ print $1 }')
		avg_time=$(echo "$times" | awk -F': ' '{ print $4 }' | awk -F'ms' '{ print $1 }')
		min_time=${min_time:-0}
		avg_time=${avg_time:-0}
		max_time=${max_time:-0}
		min_time=$(echo "$min_time" "$micros" | awk '{printf "%3.0f\n",$1*$2}')
		avg_time=$(echo "$avg_time" "$micros" | awk '{printf "%3.0f\n",$1*$2}')
		max_time=$(echo "$max_time" "$micros" | awk '{printf "%3.0f\n",$1*$2}')
		[ "$min_time" -lt "$min" ] && min="$min_time"
		[ "$max_time" -gt "$max" ] && max="$max_time"
		avg_time_sum=$((avg_time_sum+avg_time))
		sleep "${inter_time}"
	done

	failure_count=$((nbr_of_rep-success_count))
	[ $success_count -gt 0 ] && avg_time=$((avg_time_sum/success_count)) || avg_time=0
	min_time=$min
	max_time=$max

	json_init
	json_add_string "Status" "Complete"
	json_add_string "IPAddressUsed" "${ip_addr_used}"
	json_add_int "SuccessCount" "${success_count}"
	json_add_int "FailureCount" "${failure_count}"
	json_add_int "MinimumResponseTime" "${min_time}"
	json_add_int "AverageResponseTime" "${avg_time}"
	json_add_int "MaximumResponseTime" "${max_time}"
	json_dump

	# Store data in dmmap_diagnostics for both protocols (cwmp/usp)
	[ "${proto}" = "both_proto" ] && {
		$UCI_SET_BBF_DMMAP dmmap_diagnostics.udpechodiag.DiagnosticState="Complete"
		$UCI_SET_BBF_DMMAP dmmap_diagnostics.udpechodiag.IPAddressUsed="${ip_addr_used}"
		$UCI_SET_BBF_DMMAP dmmap_diagnostics.udpechodiag.SuccessCount="${success_count}"
		$UCI_SET_BBF_DMMAP dmmap_diagnostics.udpechodiag.FailureCount="${failure_count}"
		$UCI_SET_BBF_DMMAP dmmap_diagnostics.udpechodiag.MinimumResponseTime="${min_time}"
		$UCI_SET_BBF_DMMAP dmmap_diagnostics.udpechodiag.AverageResponseTime="${avg_time}"
		$UCI_SET_BBF_DMMAP dmmap_diagnostics.udpechodiag.MaximumResponseTime="${max_time}"
		$UCI_COMMIT_BBF_DMMAP
	}
}

if [ "$1" = "list" ]; then
	udpecho_list
elif [ -n "$1" ]; then
	udpecho_launch "$1"
else
	udpecho_error "Error_Internal" "1"
fi
