#!/bin/bash
# rdl_prometheus

PROM_DIR=/var/prometheus-node-exporter

help() {
    cat -v <<EOF
$(basename "$0") ( --help | COMMAND [ARG ...] )

 Eval COMMAND with ARGs and put its exit status and timestamp into
prometheus text file dir (default: $PROM_DIR).

 COMMAND is stripped of any suffix beginning with a '.' and the result
must only contain '_' and lowercase letters.

Options

 --help		print this help

Environment

 PROM_DIR	prometheus text file dir

 RDL_PROM_LINES additional lines, can be set in COMMAND. Note:
                RDL_PROM_LINES is not checked and prometheus might not
                use the .prom file if it is not correct.

Examples:

 $ echo 'false' > test.sh; chmod 777 test.sh
 $ $(basename "$0") ./test.sh 
 $ cat /var/prometheus-node-exporter/test.prom 
 test_completion_time 1757754118
 test_status 1

 $ foo() { RDL_PROM_LINES='bar 1'; return 33; }
 $ export -f foo
 $ $(basename "$0") foo
 $ cat /var/prometheus-node-exporter/foo.prom 
 foo_completion_time 1757755470
 foo_status 33
 bar 1
EOF
}

test "$1" = "--help" && help
test -z "$1" && { help; exit 1; }

eval "$@"

RETURN=$?

NAME=$(basename "$1")
NAME=${NAME%%.*}
allowed_characters='^[a-z_]+$'

[[ "$NAME" =~ $allowed_characters ]] || { help; exit 1; }

{
    echo "$NAME"_completion_time $(date +%s)
    echo "$NAME"_status $RETURN
    test -z "$RDL_PROM_LINES" || echo "$RDL_PROM_LINES"
} > /tmp/"$NAME".prom.$$

mv --force /tmp/"$NAME".prom.$$ "$PROM_DIR"/"$NAME".prom
chown prometheus:prometheus "$PROM_DIR"/"$NAME".prom

exit $RETURN
