#!/bin/sh
#
# Nagios XI failover for Princeton University
#
# Initial version written by:
# Eric Loyd (eloyd@everwatch.global)
# EverWatch Global, Inc.

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

primary="nagiosxi-p.princeton.edu"
secondary="nagiosxi-f.princeton.edu"
synconly="false"
syncname="sync"

hostname=`/bin/hostname`

while [ -n "$1" ]; do
  case "$1" in
    -H | --hostname) hostname="$2"; shift 2;;
    -S | --secondary) secondary="$2"; shift 2;;
    -P | --primary) primary="$2"; shift 2;;
    -n | --sync-name) syncname="$2"; shift 2;;
    -s | --sync-only) synconly="true"; shift 1;;
    *) shift 1;;
  esac
done

[ -z "$hostname" ] && echo "Invalid hostname." && exit 2

do_nothing() {
  echo "We are not the primary or secondary.  Doing nothing."
  exit
}

do_primary() {
  echo "We are the primary.  Creating package to send to secondary."
  ./rsync_xi.sh --prepend ${syncname} --secondary "${secondary}"
  cp /usr/local/nagiosxi/html/includes/components/custom-includes/css/header-gradient.css.primary /usr/local/nagiosxi/html/includes/components/custom-includes/css/header-gradient.css
}

do_secondary() {
  echo "We are the secondary.  Expanding package from the primary."
  syncfile=`ls -tr1 /store/backups/nagiosxi/ | tail -1`
  [ -z "$syncfile" ] && echo "No sync file ($syncfile) found." && exit 2
  ./restore_xi.sh /store/backups/nagiosxi/$syncfile
  ./nagios_startstop.sh stop
  cp /usr/local/nagiosxi/html/includes/components/custom-includes/css/header-gradient.css.secondary /usr/local/nagiosxi/html/includes/components/custom-includes/css/header-gradient.css
}

case "$hostname" in
  $primary) do_primary;;
  $secondary) do_secondary;;
  *) do_nothing
esac
