#!/bin/sh

##-----------------------------------------------------------------------
## Porgram: dbab-get-list
## Purpose: Get dnsmasq blocking list from pgl.yoyo.org
## Authors: Tong Sun (c) 2013-2021
## License: BSD license
##-----------------------------------------------------------------------

grep -n '^[[:punct:]]*$' /etc/dbab/dbab.list- && {
  echo "ERROR: Blank line(s) found in /etc/dbab/dbab.list-"
  printf "\tRemove them before proceeding.\n"
  exit 0 # so as not to break postinst
}

dbabsvr_addrs=`grep -v ^\# /etc/dbab/dbab.addr`
dbab_conf=/etc/dnsmasq.d/dbab-map.adblock.conf

# Down the DNSmasq formatted ad block list
dbab_tmp=`basename $dbab_conf`
dbab_tmp=`mktemp /tmp/$dbab_tmp.XXXXXX`
cmd="curl 'https://pgl.yoyo.org/adservers/serverlist.php?hostformat=dnsmasq&showintro=0&mimetype=plaintext' -o $dbab_tmp"
echo $cmd
eval $cmd || eval $cmd --insecure
[ $? -ne 0 ] && {
  echo "ERROR: invoking curl to retrieve the blocking list"
  exit 0 # so as not to break postinst
}

echo '# generated by dbab-get-list -- DO NOT EDIT' > $dbab_conf
[ $? -ne 0 ] && {
  echo "ERROR: updating the blocking list conf file"
  exit 0 # so as not to break postinst
}

for dbabsvr_addr in ${dbabsvr_addrs}; do
  grep -vFf /etc/dbab/dbab.list- $dbab_tmp | sed "s/127\.0\.0\.1/$dbabsvr_addr/" >> $dbab_conf
done
echo File $dbab_conf updated.

