#!/bin/bash

# This script monitors changes to the UFW (Uncomplicated Firewall) configuration.
# It computes a hash of the current UFW status (excluding status and logging lines),
# compares it to the previously stored hash, and sends a metric to Netdata via statsd
# if a change is detected. The current hash is then saved for future comparisons.

HASH_FILE="__HASH_FILE__"
MONITORED_FILE="__MONITORED_FILE__"
MONITORED_COMMAND="__MONITORED_COMMAND__"
METRIC_NAME="__METRIC_NAME__"
mkdir -p "$(dirname "$HASH_FILE")"

if [ -n "$MONITORED_COMMAND" ] && [ "$MONITORED_COMMAND" != "__MONITORED_COMMAND__" ]; then
  current_state=$(eval "$MONITORED_COMMAND")
  current_hash=$(echo "$current_state" | md5sum | awk '{print $1}')
elif [ -n "$MONITORED_FILE" ] && [ "$MONITORED_FILE" != "__MONITORED_FILE__" ]; then
  current_hash=$(md5sum "$MONITORED_FILE" | awk '{print $1}')
else
  echo "No valid MONITORED_FILE or MONITORED_COMMAND specified!"
  exit 1
fi

[ -f "$HASH_FILE" ] && previous_hash=$(cat "$HASH_FILE") || previous_hash=""

if [ "$current_hash" != "$previous_hash" ] && [ -n "$previous_hash" ]; then
  change_flag=1
else
  change_flag=0
fi

echo "$METRIC_NAME:$change_flag|g" | nc -u -w 1 localhost 8125
echo "$current_hash" > "$HASH_FILE"