#!/bin/sh
#
# Copyright (C) 2018-2026 Ycarus (Yannick Chabanois) <ycarus@zugaina.org> for OpenMPTCProuter
#
# This is free software, licensed under the GNU General Public License v2.
# See /LICENSE for more information.
#
# This script logs a timestamped event every time an interface tracked by
# omr-tracker changes state: up, down, high latency, packet loss or
# disconnection. The tracker itself already flips OMR_TRACKER_STATUS to
# ERROR (with a descriptive OMR_TRACKER_STATUS_MSG) on link loss, gateway
# loss or a latency/packet-loss threshold breach (see omr-tracker's
# OMR_TRACKER_CHECK_QUALITY logic), so this script only has to watch for a
# status transition and classify the reason from that message - it does not
# re-implement any threshold detection.
#
# Events are written by omr_events_write (lib/omr-events.sh), which also
# applies the age/size retention.

[ -z "$OMR_TRACKER_INTERFACE" ] && exit 0
# Nothing changed: this hook still runs every post-tracking cycle (throttled
# to OMR_TRACKER_POST_INTERVAL), so bail out cheaply before touching uci/fs.
[ "$OMR_TRACKER_PREV_STATUS" = "$OMR_TRACKER_STATUS" ] && exit 0

[ "$(uci -q get omr-events.settings.enabled)" = "0" ] && exit 0

. "${OMR_LIB_DIR:-/usr/share/omr/lib}/omr-events.sh"

now=$(date +%s)

case "$OMR_TRACKER_STATUS" in
	OK)    event="up" ;;
	ERROR) event="down" ;;
	*)     event="$OMR_TRACKER_STATUS" ;;
esac

# Classify the free-form tracker message into a short machine-readable
# reason so a UI/API consumer can filter or color by cause without parsing
# OMR_TRACKER_STATUS_MSG itself. Patterns mirror the exact strings the
# tracker daemon and 002-error emit (bin/omr-tracker, post-tracking.d/002-error).
msg="$OMR_TRACKER_STATUS_MSG"
case "$msg" in
	*"Packet loss is"*)          reason="packet_loss" ;;
	*"Latency is"*)               reason="high_latency" ;;
	*"Congestion score is"*)      reason="congestion" ;;
	*"link down"*)                 reason="link_down" ;;
	*"gateway down"*)              reason="gateway_down" ;;
	*"No answer from server"*)     reason="no_answer" ;;
	*"No access to server API"*)   reason="no_answer" ;;
	*"No IP"*|*"ip issues"*)       reason="no_ip" ;;
	*"Glorytun-UDP path"*)         reason="vpn_path" ;;
	"")
		if [ "$event" = "up" ]; then
			reason="recovered"
		else
			reason="unknown"
		fi
	;;
	*) reason="other" ;;
esac

# JSON-escape the free-form message (backslash and double-quote only, the
# tracker never emits control characters here)
msg_esc=$(printf '%s' "$msg" | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g')

_jval() {
	if [ -n "$1" ] && [ "$1" != "--" ]; then
		echo "$1"
	else
		echo "null"
	fi
}

# "ts" must stay the first key (see omr_events_write)
omr_events_write "$now" "$(printf '{"ts":%s,"interface":"%s","device":"%s","event":"%s","reason":"%s","message":"%s","latency":%s,"loss":%s}' \
	"$now" "$OMR_TRACKER_INTERFACE" "$OMR_TRACKER_DEVICE" "$event" "$reason" "$msg_esc" \
	"$(_jval "$OMR_TRACKER_LATENCY")" "$(_jval "$OMR_TRACKER_LOSS")")"

logger -t omr-events "$OMR_TRACKER_INTERFACE ($OMR_TRACKER_DEVICE) $event: ${msg:-$reason}"

exit 0
