#!/bin/sh

set -eu

UNBOUND=/usr/sbin/unbound

usage() {
	echo "${0##*/} -u url [-w whitelist.file] [-U /path/to/unbound] [-R] [-d] [-v] [-h]
    -u url               url to StevenBlack hosts
    -w whitelist.file    exclude file (grep format)
    -U /path/to/unbound  default: $UNBOUND
    -R                   reload unbound
    -d                   mode debug
    -v                   mode verbose
    -h                   this message

Example:

$0 -u https://raw.githubusercontent.com/StevenBlack/hosts/master/alternates/fakenews-gambling-porn-social/hosts -U /usr/sbin/local-unbound -R

$0 -u http://sbc.io/hosts/alternates/fakenews-gambling-porn-social/hosts -w whitelist.ads -R -d

$0 -u https://hostfiles.frogeye.fr/firstparty-trackers-hosts.txt
"
}

# TODO on ne fait pas que ads, on peut aussi faire tracker
# TODO passer "ads" en param ?
# TODO on ne peut pas avoir plusieurs fichiers car on ne peut avoir qu'une view

QUIET="-q"
RELOAD=
URL=
WHITELIST=

args=$(getopt u:w:U:Rdvh $*)
if [ $? -ne 0 ]; then
	echo $USAGE
	exit 2
fi
set -- $args
while :; do
	case "$1" in
	-u) URL=$2; shift; shift;;
	-U) UNBOUND=$2; shift; shift;;
	-R) RELOAD=1; shift;;
	-w) WHITELIST=$2; shift; shift;;
	-d) set -x; shift;;
	-v) QUIET=; shift;;
	-h) usage; exit 0;;
	--) shift; break;;
	esac
done

if [ -z $URL ]; then
	echo "Error: url required"
	usage
	exit 1
fi

TMPFILE=$(mktemp $QUIET -t host.ads.XXXXXX)
WRKDIR="$($UNBOUND-checkconf -o directory)/conf.d"

if [ ! -w $WRKDIR ]; then
	echo "Error: '$WRKDIR' not writable. Exit"
	exit 1
fi

clean_up() {
	rm -f $TMPFILE
}

trap clean_up EXIT

case $(uname -s) in
FreeBSD)
	fetch $QUIET --output=$TMPFILE $URL
	;;
OpenBSD)
	ftp -o $TMPFILE $URL
	;;
Linux)
	wget $QUIET -O $TMPFILE $URL
	;;
*)
	echo "OS not yet supported. Can't fetch url. Exit"
	exit 1
esac

AWK_PROG='NF == 2 && $1 == "0.0.0.0" && $2 ~ /^[a-z0-9]/ { print "local-zone: \"" $2 "\" static" }'

echo "view:
name: ads
view-first: yes
" > $WRKDIR/ads.conf.tmp
CMD="awk '$AWK_PROG' $TMPFILE"
if [ -n "$WHITELIST" ]; then
	CMD="$CMD | grep --file=$WHITELIST --invert-match"
fi
eval "$CMD >> $WRKDIR/ads.conf.tmp"

$UNBOUND-checkconf $WRKDIR/ads.conf.tmp > /dev/null
mv $WRKDIR/ads.conf.tmp $WRKDIR/ads.conf
[ -n $RELOAD ] && $UNBOUND-control $QUIET reload
