#!/usr/bin/env sh

set -e

: << =cut

=head1 NAME

libretranslate - Monitor requests on a LibreTranslate system

=head1 APPLICABLE SYSTEMS

LibreTranslate https://github.com/LibreTranslate/LibreTranslate

=head1 CONFIGURATION

Requires LT_METRICS of LibreTranslate to be set to true. You may specify the 
URL where to get the statistics.

 url      - URL of LibreTranslate metrcs
 max_time - Timeout curl - defaults to 3 seconds

 [libretranslate_requests]
 env.url http://127.0.0.1:5000/metrics
 env.max_time 3

=head1 AUTHOR

Copyright (C) 2025 Sebastian L. (https://momou.ch)

=head1 LICENSE

GPLv2

=head1 MAGIC MARKERS

 #%# family=auto
 #%# capabilities=autoconf

=cut

. "$MUNIN_LIBDIR/plugins/plugin.sh"

url=${url:-"http://127.0.0.1:5000/metrics"}
max_time=${max_time:-3}

case $1 in
	autoconf)
		if [ -x "$(command -v curl)" ]; then
			curl -s -f -m "$max_time" -I -X GET "$url" | grep 'OK' && echo "yes" && exit 0 || echo "no (invalid or empty response from metrics endpoint ($url))" && exit 1
		else
			echo "no (curl not found)" && exit 0
		fi
	;;

    config)
        echo "graph_title Requests on LibreTranslate"
        echo "graph_category appserver"
        echo "graph_vlabel translation requests"
        echo "graph_info Requests on libretranslate"
        echo "graph_args --base 1000 --lower-limit 0"
        echo "requests.label requests"
        echo "requests.info Translation requests"
        echo "requests.type DERIVE"
        echo "requests.min 0"
        exit 0
    ;;
esac

if counts=$(curl -s -f -m "$max_time" -X GET "$url"); then
	value=0
	counts=$(echo $counts | grep libretranslate_http_request_duration_seconds_count | grep  -oE "status=\"200\"}\ [0-9]+" | cut -d ' ' -f 2)
	for count in $counts
	do
		if [ -n "$count" ]; then
			value=$(( value + count ))
		fi
	done
	echo "requests.value $value"
else
	echo "requests.value U"
fi
