#!/bin/bash

. @PREFIX@/etc/varnish/varnish.conf

VARNISHD_PID="@PREFIX@/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)
        @PREFIX@/sbin/varnishd $VARNISHD_OPTS -P $VARNISHD_PID
    ;;
    stop)
        [[ $PID ]] && kill $PID &>/dev/null
    ;;
    restart)
        $0 stop
        sleep 1
        $0 start
    ;;
    reload)
        @PREFIX@/sbin/varnish-vcl-reload $VARNISH_CFG
    ;;
    *)
        echo "usage: $0 {start|stop|restart|reload}"
    ;;
esac
