#!/bin/sh
# Copyright 2020 Jordan Geoghegan <jordan@geoghegan.ca>

# Permission to use, copy, modify, and/or distribute this software for any 
# purpose with or without fee is hereby granted, provided that the above 
# copyright notice and this permission notice appear in all copies.

# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH 
# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
# AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM 
# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE 
# OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR 
# PERFORMANCE OF THIS SOFTWARE.

# Version 0.3 "Time in a Bottle" -- Released March 10th 2020

# In loving memory of Ron Sather

# Download and parse StevenBlack hosts file into unbound compatible format

tmpfile=$(mktemp)

clean_up () {
	rm -f "$tmpfile"
}

abort () {
	printf "\nBad Data in /var/unbound/etc/adblock.conf! Reverting changes and bailing out!\n\n" ; cp /dev/null /var/unbound/etc/adblock.conf ; clean_up ; exit 1
}

dl_abort () {
	printf "\nFailed to Download One or More Blocklists! Quitting Without Making Changes...\n\n" ; clean_up ; exit 1
}

list_update_abort () {
	printf "\nFailed to update /var/unbound/etc/adblock.conf! Please ensure the file has correct permissions and that the partition has free space!\n\n" ; clean_up ; exit 1
}

# Add blocklists below, one URL per line
# Blocklists MUST be in /etc/hosts format
blocklists=$(cat <<'EOF'
https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts
EOF
)

# Do not edit this unless you know what you're doing
echo "$blocklists" |  xargs ftp -o -  > "$tmpfile" || dl_abort
nice awk '{sub(/\r$/,"")} {sub(/^127\.0\.0\.1/,"0.0.0.0")} BEGIN { OFS = "" } NF == 2 && $1 == "0.0.0.0" { print "local-zone: \"", $2, "\" static"}' "$tmpfile" | tr '[:upper:]' '[:lower:]' | sort -u > /var/unbound/etc/adblock.conf || list_update_abort
unbound-checkconf || abort
doas rcctl reload unbound || abort

# Clean up after ourselves
clean_up
