#!/bin/bash

. /opt/local/etc/varnish/varnish.conf

VARNISHD_PID="/opt/local/var/run/varnish/varnish.pid"

if [[ -r $VARNISHD_PID ]]; then
    read -r PID < "$VARNISHD_PID"
    ps -p $PID &> /dev/null
    CHECK=$?
    if [[ "x$CHECK" == "x1" ]]; then
      unset PID
      rm -f "$VARNISHD_PID"
    fi
fi

case $1 in
    start)
        /opt/local/sbin/varnishd $VARNISHD_OPTS -P $VARNISHD_PID
    ;;
    stop)
        [[ $PID ]] && kill $PID &>/dev/null
    ;;
    restart)
        $0 stop
        sleep 1
        $0 start
    ;;
    reload)
        /opt/local/sbin/varnish-vcl-reload $VARNISH_CFG
    ;;
    *)
        echo "usage: $0 {start|stop|restart|reload}"
    ;;
esac
