#!@l_bash@
##
##  squidguard-update -- SquidGuard Database Update
##

db_cfg="@l_prefix@/etc/squidguard/squidguard.conf"
db_dir="@l_prefix@/var/squidguard/db"
db_url="http://squidguard.mesd.k12.or.us/blacklists.tgz"

echo "++ ensuring existence of database files"
for file in `egrep '(domainlist|urllist)' $db_cfg | sed -e 's/^ *[^ ][^ ]* *//'`; do
    dir=`echo $file | sed -e 's;/[^/]*$;;'`
    if [ ! -d $db_dir/$dir ]; then
        @l_shtool@ mkdir -f -p -m 755 $db_dir/$dir
    fi
    if [ ! -f $db_dir/$file ]; then
        @l_shtool@ install -c -m 644 /dev/null $db_dir/$file
    fi
done

echo "++ downloading blacklists:"
echo "   $db_url"
i=0
while [ $i -lt 3 ]; do
    @l_prefix@/bin/curl -s -o ${db_dir}/blacklists.tar.gz ${db_url} || exit $?
    if [ $? -eq 0 ]; then
        break
    else
        rm -f ${db_dir}/blacklists.tar.gz >/dev/null 2>&1 || true
        sleep 10
    fi
    i=$(($i + 1))
done
if [ ! -f ${db_dir}/blacklists.tar.gz ]; then
    echo "squidguard-update:ERROR: unable to download latest blacklists" 1>&2
    exit 1
fi

echo "++ unpacking blacklists:"
cd ${db_dir} || exit $?
@l_gzip@ -d -c blacklists.tar.gz |\
@l_tar@ xf -
rm -f ${db_dir}/blacklists.tar.gz

echo "++ generating database files from blacklists:"
@l_prefix@/bin/squidguard -C all </dev/null

echo "++ triggering configuration update for Squid:"
@l_prefix@/sbin/squid -k reconfigure >/dev/null 2>&1 || true

