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

LC_ALL=C
export LC_ALL

CONFIG=/etc/squid/conf.d/debian-edu.conf

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

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

defaultcachedir=/var/spool/squid

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/service ] ; then
	service squid reload
    else
	systemctl reload squid.service
    fi
    echo "info: Squid reloaded with changed configuration"
else
    echo "info: Squid configuration not changed"
fi
