#!/bin/bash
#----------------------------------------------------------------------
# copyright (C) 2011 Firewall Services
# daniel@firewall-services.com
# 
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#               
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#               
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
# 
#----------------------------------------------------------------------

# This function check if the given category is disabled
function cat_is_disabled(){
  cat=$1
  local ret=0
  for D in $(echo $DISABLED_CAT | sed -e 's/[;,]/ /g'); do
    if [ "$D" == "$cat" ]; then
      local ret=1
      break
    fi
  done
  echo $ret
}

/bin/mkdir -p /var/squidGuard/blacklists/{black,white}

# Be sure those files exists
for F in "black/domains" "black/urls" "white/domains" "white/urls"; do
  if [ \! -e /var/squidGuard/blacklists/$F ]; then
    touch /var/squidGuard/blacklists/$F
  fi
done

UPDATE=$(/sbin/e-smith/db configuration getprop squidguard AutoUpdate || echo enabled)
DISABLED_CAT=$(/sbin/e-smith/db configuration getprop squidguard DisabledCategories)

if [ "$UPDATE" == "enabled" ]; then
  # Update database from the University of Toulouse
  /usr/bin/rsync -rzPq ftp.univ-tlse1.fr::blacklist/dest/ /var/squidGuard/blacklists/
fi

# Rebuild database only if something changed
for CAT in $(ls /var/squidGuard/blacklists/); do
  if [ "$(cat_is_disabled $CAT)" == "1" ]; then
    echo "$CAT is disabled, skiping"
    continue
  fi
  for TYPE in domains urls; do
    if [ -f /var/squidGuard/blacklists/$CAT/$TYPE ]; then
      OLDMD=$(cat /var/squidGuard/blacklists/$CAT/$TYPE.md5 2>/dev/null)
      NEWMD=$(md5sum /var/squidGuard/blacklists/$CAT/$TYPE | cut -d' ' -f1)
      if [ "$OLDMD" != "$NEWMD" ]; then
        echo "$CAT/$TYPE has changed, database needs to be updated"
        rm -f /var/squidGuard/blacklists/$CAT/$TYPE.db
        /usr/bin/squidGuard -P -C $CAT/$TYPE
        if [ -e /var/squidGuard/blacklists/$CAT/$TYPE.db ]; then
          md5sum /var/squidGuard/blacklists/$CAT/$TYPE | cut -d' ' -f1 > \
            /var/squidGuard/blacklists/$CAT/$TYPE.md5
        fi
      else
        echo "$CAT/$TYPE hasn't changed, no database update needed"
      fi
    fi
  done
done

chown -R squid:squid /var/squidGuard/blacklists
chown -R squid:squid /var/log/squidGuard/*
chmod 640 /var/log/squidGuard/*

# Reload squid configuration
/usr/sbin/squid -k reconfigure


