#!/usr/bin/env bash
#
# Copyright (C) 2003 VA Linux Systems Japan, K.K.
#
# LICENSE NOTICE
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#

set -e

eval `ultrapossum-config init`

tmp=`tempfile`
trap "/bin/rm -f $tmp; eval `ultrapossum-config term`" 0

sanity() {
  if test "x$VIRTUALSLAVE" != "x"; then
    for s in $SLAVES $VIRTUALSLAVE
    do
      load=`getent hosts $s | head -1 | awk -F' ' '{print $2;}'`
      if test "x$load" = "x"; then
        echo "E: can't resolve FQDN of $s" 1>&2
        exit 1
      fi
    done
  fi
}

configure() {
  sanity
  if test "x$SLAVES" = "x"; then
    echo "W: No slaves defined. slave balancing disabled." 1>&2
    remove
  elif test "x$VIRTUALSLAVE" = "x"; then
    echo "W: No virtual slave server defined. slave balancing disabled" 1>&2
    remove
  else

    load=`getent hosts $VIRTUALSLAVE | head -1 | awk -F' ' '{print $2;}'`

    cat > $DNSBALANCEDB <<EOF
;
; BIND data file for local loopback interface
;
\$TTL    604800
@       IN      SOA     $load. root.$load. (
                      `date +%s`	; Serial
                         604800         ; Refresh
                          86400         ; Retry
                        2419200         ; Expire
                              0 )       ; Negative Cache TTL
;
@	IN	NS	`getent hosts $HOST | head -1 | awk -F' ' '{print $2;}'`.

EOF

    for s in $SLAVES
    do
      for h in `getent hosts $s | cut -d' ' -f1`
      do
        echo "@	IN	A	$h" >> $DNSBALANCEDB
      done
    done
 
    if test "x$ULTRAPOSSUMMARK" = "xULTRAPOSSUM"; then
      add_startmark "//" "DNSBALANCE" > $tmp
      echo "zone \"$load\" {" >> $tmp
      echo "	type master;" >> $tmp
      echo "	file \"$DNSBALANCEDB\";" >> $tmp
      echo "};" >> $tmp
      add_endmark "//" "DNSBALANCE" >> $tmp
      add_end_vaconf $NAMEDCONF $tmp "DNSBALANCE"
    fi
  fi

}

remove() {
  strip_vaconf $NAMEDCONF "DNSBALANCE"
  /bin/rm -f $DNSBALANCEDB
}

case "x$1" in
        xconfigure)
                configure
		/bin/rm -f $CONFSTATUS
        ;;
        xremove)
                remove
		/bin/rm -f $CONFSTATUS
        ;;
        xsanity)
                sanity_check
        ;;
        x)
                echo "Usage: $0 <configure|remove>" 1>&2
                exit 1
        ;;
        x*)
                echo "Unknown argument: $1" 1>&2
                exit 1
        ;;
esac

