#!/bin/bash
set -eu
shopt -s nullglob

mkdir -p /var/vcap/sys/log/bind9 \
         /var/vcap/sys/run/named
exec >> /var/vcap/sys/log/bind9/named.log 2>&1

PATH=$PATH:/var/vcap/packages/bind9/sbin
PATH=$PATH:/var/vcap/packages/bind9/bin
export PATH

 datadir="/var/vcap/sys/run/named/data"
 config=/var/vcap/jobs/named/config/named.conf
   ttar=/var/vcap/jobs/named/bin/ttar
  zones=/var/vcap/jobs/named/config/zones.ttar
pidfile=/var/vcap/sys/run/named/named.pid

pids=
if [[ -f $pidfile ]]; then
  pids=$(cat $pidfile)
fi


case $1 in
  start)
    if test -n "$pids" && kill -0 $pids >/dev/null 2>&1; then
      echo "[$(date)] bind seems to be running already (pid $pids, from $pidfile)!"
      exit 1
    fi

    # re-inflate zone files
    rm -f ${datadir}/*.db
    mkdir -p ${datadir}
    $ttar < $zones

    # check configuration
    echo "[$(date)] checking named configuration..."
    named-checkconf $config
    echo "[$(date)] named configuration OK"
    echo

    for file in ${datadir}/*.db; do
      zone=${file##*/}
      zone=${zone%%.db}
      echo "[$(date)] checking zone '${zone}' (in ${file})..."
      named-checkzone ${zone} ${file}
      echo "[$(date)] zone '${zone}' OK"
      echo
    done
    echo "[$(date)] all zones OK"
    echo

    echo $$ > $pidfile
    echo "[$(date)] bind named starting up (pid $$)"
    exec named -g -c $config
    ;;

  stop)
    if [[ -z "$pids" ]]; then
      pids=$(pgrep named)
    fi

    n=250
    echo "[$(date)] sending named procs ($pids) a SIGTERM..."
    kill -TERM $pids || true
    while test -n "$pids" && kill -0 $pids >/dev/null 2>&1; do
      if [[ $n < 1 ]]; then
        echo "[$(date)] named is still running; sending a SIGKILL..."
        kill -9 $pids || true
        sleep 0.5
        break
      fi
      sleep 0.1
      n=$(( $n - 1 ))
    done
    rm -f $pidfile
    ;;

  *)
    echo "Usage: named {start|stop}"
    ;;

esac
exit 0
