#!/bin/sh
# Urutau: applies the operator's unban requests written by Urutau (UI button)
# to /var/log/urutau-enforce/unban.log. One line per request:
#   2026-11-15T05:00:00Z urutau unban ip=203.0.113.7 allow=86400
# The address is validated strictly; fail2ban unbans it from every jail and,
# with allow>0, ignores it in every jail for that many seconds (pentests).
set -eu
log=/var/log/urutau-enforce/unban.log
state=/var/lib/urutau/unban.offset
[ -f "$log" ] || exit 0
mkdir -p /var/lib/urutau
off=$(cat "$state" 2>/dev/null || echo 0)
size=$(stat -c %s "$log")
[ "$size" -lt "$off" ] && off=0 # rotated or truncated
tail -c +"$((off + 1))" "$log" | head -n 1000 | while IFS= read -r line; do
	ip=$(printf '%s\n' "$line" | sed -n 's/^[0-9TZ:-]* urutau unban ip=\([0-9a-fA-F.:]\{2,45\}\) allow=\([0-9]\{1,7\}\)$/\1/p')
	allow=$(printf '%s\n' "$line" | sed -n 's/^.* allow=\([0-9]\{1,7\}\)$/\1/p')
	[ -n "$ip" ] || continue
	# only literal IPv4 / IPv6 addresses (no CIDR, no names)
	python3 -c 'import ipaddress,sys; ipaddress.ip_address(sys.argv[1])' "$ip" 2>/dev/null || continue
	fail2ban-client unban "$ip" >/dev/null 2>&1 || true
	logger -t urutau-unban "unban $ip allow=${allow:-0}"
	if [ "${allow:-0}" -gt 0 ]; then
		for j in $(fail2ban-client status | sed -n 's/.*Jail list:[[:space:]]*//p' | tr ',' ' '); do
			fail2ban-client set "$j" addignoreip "$ip" >/dev/null 2>&1 || true
		done
		systemd-run --quiet --on-active="${allow}s" --unit="urutau-allow-end-$(printf '%s' "$ip" | tr ':.' '--')" \
			/bin/sh -c "for j in \$(fail2ban-client status | sed -n 's/.*Jail list:[[:space:]]*//p' | tr ',' ' '); do fail2ban-client set \$j delignoreip $ip; done" 2>/dev/null || true
	fi
done
echo "$size" > "$state"
