#!/bin/bash
#
# squid         This shell script takes care of starting and stopping
#               Squid Internet Object Cache
#
# Default settings:
# user: nobody
# cache_dir: /var/log/squid/cache
# pidfile: /var/log/squid/logs/squid.pid
# config: /etc/squid.conf

PATH=/usr/bin:/sbin:/bin:/usr/sbin
export PATH

# check if the squid conf file is present
[ -f /etc/squid/squid.conf ] || exit 0

# determine the name of the squid binary
[ -f /usr/sbin/squid ] && SQUID=/usr/sbin/squid
[ -z "$SQUID" ] && exit 0

# determine which one is the cache_dir directory
CACHE_DIR=`sed -e 's/#.*//g' /etc/squid/squid.conf | \
        grep cache_dir | sed -e 's/cache_dir ufs//' | \
        cut -d ' ' -f 2`
[ -z "$CACHE_DIR" ] && CACHE_DIR=/var/log/squid/cache

# determine which one is the squid owner
SQUID_OWNER=`sed -e 's/#.*//g' /etc/squid/squid.conf | \
        grep cache_effective_user | sed -e 's/cache_effective_user //'`
[ -z "$SQUID_OWNER" ] && SQUID_OWNER=nobody

# determine the location of squid.pid
SQUID_PID=`sed -e 's/#.*//g' /etc/squid/squid.conf | \
        grep pid_filename | sed -e 's/pid_filename //'`
[ -z "$SQUID_PID" ] && SQUID_PID=/var/log/squid/logs/squid.pid

# default squid options
# -D disables initial dns checks. If you most likely will not to have an
#    internet connection when you start squid, uncomment this
#SQUID_OPTS="-D"

case "$1" in
start)
    echo -n "Starting $SQUID: "
    for adir in $CACHE_DIR; do
        if [ ! -d $adir/00 ]; then 
             echo -n "init_cache_dir $adir... "
	     mkdir $CACHE_DIR
	     chown -R $SQUID_OWNER $CACHE_DIR
	     chown -R $SQUID_OWNER /var/log/squid
             $SQUID -z -F 2>/dev/null
        fi
    done
    $SQUID $SQUID_OPTS &
    echo $SQUID 
    ;;

stop)
    echo -n "Stopping $SQUID: "
    $SQUID -k shutdown &
    while : ; do
        [ -f $SQUID_PID ] || break
        sleep 2 && echo -n "." 
    done
    echo "done"
    ;;

restart)
    $SQUID $SQUID_OPTS -k reconfigure
    exit $?
    ;;

status)
    $SQUID -k check
    exit $?
    ;;

probe)
    exit 0;
    ;;

*)
    echo "Usage: $0 {start|stop|status|restart}"
    exit 1
esac

exit 0
