#!/bin/sh
# alpha-f2b-adminip — fail2ban `ignorecommand`: "is this address the panel's own admin?"
#
# The panel appends every address it serves an AUTHENTICATED request to into
# ADMIN_IPS, one "<ip> <last-seen-epoch>" per line (auth_note_admin_ip()).
# The web jails ask this script before banning, so the server can never lock
# out the person who owns it.
#
#   exit 0 = ignore this address      exit 1 = treat it like anyone else
#
# Why this exists: Payment Studio rendered a preview iframe per payment link,
# and order-only links answer 404 by design (there is nothing to sell without a
# real order), so opening that one screen twice inside the jail's 120 s window
# was 26 x 404 = an instant ban of the admin's own IP. Those 404s are fixed,
# but a static `ignoreip` cannot follow an admin on a dynamic address — this
# can, because it learns the address from the act of signing in.
#
# Deliberately NOT applied to sshd / postfix / dovecot / the panel-login jail:
# those protect credentials, and a shared carrier NAT would extend the pass to
# whoever else sits behind it.

set -u

ADMIN_IPS=/var/www/alpha-private/admin-ips.txt
TTL=604800                     # 7 days since the last signed-in request from this address

ip="${1:-}"
[ -n "$ip" ] || exit 1
[ -r "$ADMIN_IPS" ] || exit 1

now=$(date +%s) || exit 1

# The redirect is on the loop, not a pipe, so `exit` here exits the script.
while read -r a ts _rest; do
  [ "$a" = "$ip" ] || continue
  case "$ts" in '' | *[!0-9]*) exit 1 ;; esac
  [ $((now - ts)) -lt $TTL ] || exit 1
  exit 0
done < "$ADMIN_IPS"

exit 1
