#!/bin/sh
#
# Author: Dominic Reich <quick.hat4396@qtztsjosmprqmgtunjyf.com>
# export the blacklist table from pf (pfctl -t blacklist)
# to the blocked.txt file on my http webroot

if [[ $USER == "root" ]]; then
  echo >&2 "user must not be root! exiting."
  exit 1
fi

# add ips to table blacklist
(for ip in `cat ~/ips`; do echo $ip;done) | xargs doas pfctl -t blacklist -T add

# save sorted table blacklist into file /etc/blacklist
doas pfctl -t blacklist -T show | sort -h | uniq | doas tee /etc/blacklist 1>/dev/null

# continue to update the blocked.txt file in the webserver root
# available at http://bor.oe7drt.com/blocked.txt
BLOCKEDTXT=/home/dominic/pub/blocked/web.txt
FILEBACKUP=3

if [ ${FILEBACKUP} -ne 0 ]; then
	cp ${BLOCKEDTXT} ${BLOCKEDTXT}.$(date +%Y%m%d)
fi

BACKUPCOUNT=$(ls ${BLOCKEDTXT}.* | wc -l)
BACKUPSTODELETE=$(expr ${BACKUPCOUNT} - ${FILEBACKUP})
if [ ${BACKUPCOUNT} -gt ${FILEBACKUP} ]; then
	for f in $(ls -tr ${BLOCKEDTXT}.* | head -${BACKUPSTODELETE})
	do
		rm ${f}
	done
fi

rm -f ~/ips

doas pfctl -t blacklist -T show | tee ${BLOCKEDTXT} 1>/dev/null

doas pfctl -t blacklist -T test $(w | tail -1 | awk '{ print $3}')

echo

#doas pfctl -nf /etc/pf.conf

doas pfctl -vf /etc/pf.conf

echo doas pfctl -ss
echo doas pfctl -Fs
