#!/bin/bash
#
# A custom script to update the filtered dns records for dns masq
# setting all of these domains to 127.0.0.1 causes ads to not be displayed
echo "`date`: dnsmasq adblock update script started" >> /var/log/firewall.log
exclude[0]=blogsmithmedia
exclude[1]=doubleclick
exclude[2]=techepics
# remove old temp file if it is there
if [ -e /tmp/adblockhosts ]
then
rm /tmp/adblockhosts
fi
# grab the raw list from the website
wget -q -O /tmp/adblockhosts "http://pgl.yoyo.org/adservers/serverlist.php?hostformat=hosts&showintro=0&startdate%5Bday%5D=&startdate%5Bmonth%5D=&startdate%5Byear%5D=&mimetype=plaintext"
# temp file will have zero size if wget fails
if [ -s /tmp/adblockhosts ]
then
# if the temp formated adblock file exists, delete it
if [ -e /tmp/dnsmasq.adblock.conf ]
then
rm /tmp/dnsmasq.adblock.conf
fi
# the list is not formated properly for dnsmasq so we have to change that
cat /tmp/adblockhosts | grep 127.0.0.1 | awk '{print "address=/"$2"/127.0.0.1"}' >> /tmp/dnsmasq.adblock.conf
if [ -s /tmp/dnsmasq.adblock.conf ] # did everything parse ok?
then
# remove any lines containing text from the exclude array
for siteallowed in "${exclude[@]}"
do
echo removing $siteallowed from list
if [ -e /tmp/adblockhosts ]
then
rm /tmp/adblockhosts
fi
cat /tmp/dnsmasq.adblock.conf | grep -v $siteallowed >> /tmp/adblockhosts
if [ -s /tmp/adblockhosts ]
then
rm /tmp/dnsmasq.adblock.conf
mv /tmp/adblockhosts /tmp/dnsmasq.adblock.conf
fi
done
# if the adblock file exists, delete it
if [ -e /etc/dnsmasq.adblock.conf ]
then
rm /etc/dnsmasq.adblock.conf
fi
mv /tmp/dnsmasq.adblock.conf /etc/dnsmasq.adblock.conf
if [ -s /etc/dnsmasq.adblock.conf ] # check that everything went ok
then
dnsblocks=$(cat /etc/dnsmasq.adblock.conf | grep -c 127.0.0.1)
echo "`date`: dnsmasq adblock update script loaded $dnsblocks blocked dns entires" >> /var/log/firewall.log
/etc/init.d/dnsmasq stop
/etc/init.d/dnsmasq start
echo "`date`: dnsmasq adblock update script completed, dnsmasq restarted" >> /var/log/firewall.log
else
echo "`date`: dnsmasq adblock update script failed, /etc/dnsmasq.adblock.conf is empty" >> /var/log/firewall.log
fi
else
echo "`date`: dnsmasq adblock update script failed, parse failed" >> /var/log/firewall.log
fi
else
echo "`date`: dnsmasq adblock update script failed, failed to fetch list" >> /var/log/firewall.log
fi