#!/bin/bash
#
# Update cache size in squid.conf to be 80% of the partition size

LC_ALL=C
export LC_ALL

CONFIG=/etc/squid3/squid.conf

[ ! -f /etc/default/squid3 ] || . /etc/default/squid3

if [ "$1" ] ; then
    squidconf="$1"
else
    squidconf="$CONFIG"
fi

if [ "$2" ] ; then
    fillpercent="$2"
else
    fillpercent=80
fi

defaultcachedir=/var/spool/squid3

cachedir="$(grep '^cache_dir ufs ' $squidconf | awk '{print $3}')"
if [ -z "$cachedir" ] ; then
    echo "warning: Unable to find cache_dir entry in $squidconf, adding it."
    cat <<EOF >> $squidconf
cache_dir ufs $defaultcachedir 100 16 256
EOF
    cachedir=$defaultcachedir
fi
newconf=false
partsize="$(df -mP $cachedir/. | grep $cachedir | awk '{print $2}')"
if [ "$partsize" ] && [ 0 -lt "$partsize" ] ; then
    newcachesize=$(( $partsize * $fillpercent / 100 ))
    echo "info: Updating $squidconf to use cache_dir size $newcachesize MB"

    sed "s%^\\(cache_dir ufs $cachedir\\) [0-9]\\+ \([0-9]\\+ [0-9]\\+\)%\\1 $newcachesize \\2%" \
	< "$squidconf" > "$squidconf.new" \
	&& mv "$squidconf.new" "$squidconf"
    newconf=true
else
    echo "error: Unable to calculate size of partition for $cachedir"
fi

if $newconf ; then
    if [ -x /usr/sbin/invoke-rc.d ] ; then
	invoke-rc.d squid3 reload
    else
	/etc/init.d/squid3 reload
    fi
else
    echo "info: Squid configuration not changed"
fi
