#!/bin/bash

verbose=0
set -e

KEYFILE="/usr/local/nagios/.ssh/unifiDownload"

while getopts "i:H:S:u:v" opt; do
    case $opt in
        i ) KEYFILE="$OPTARG"
            ;;
        u ) USRNAME="$OPTARG"
            ;;
        H ) HSTNAME="$OPTARG"
            ;;
        S ) SECONDARY="$OPTARG"
            ;;
        v ) verbose=1
            ;;
    esac
done

if ! [[ $HSTNAME ]] ; then
    echo "Please provide a primary gateway hostname with -H."
    exit 3
fi
if ! [[ $USRNAME ]] ; then
    echo "Please provide a username with the -u flag."
    exit 3
fi
if ! [[ $SECONDARY ]] ; then
    echo "Please enter a secondary gateway hostname with -S."
    exit 3
fi
if ! [[ $KEYFILE ]] ; then
    echo "Please provide a keyfile location with the -i flag."
    exit 3
fi


# Log into both gateways, grab the single <revision></revision> block which gives last revision time.
if [[ $verbose -eq 1 ]] ; then echo "Retrieving last modification time from $HSTNAME." ; fi
resultPri=$(ssh -i $KEYFILE $USRNAME@$HSTNAME "sed -n '/<revision>/,/<\/revision>/p' /conf/config.xml")
if [[ $verbose -eq 1 ]] ; then echo "Retrieving sync IP from $HSTNAME" ; fi
secIP=$SECONDARY
if [[ $verbose -eq 1 ]] ; then echo "Raw secondary: $secIP" ; fi
if [[ $verbose -eq 1 ]] ; then echo "Retrieving last modification time from $secIP." ; fi
resultSec=$(ssh -i $KEYFILE $USRNAME@$secIP "sed -n '/<revision>/,/<\/revision>/p' /conf/config.xml")

if [[ $verbose -eq 1 ]] ; then echo "Raw result from primary:"; echo "$resultPri"; echo ; fi
if [[ $verbose -eq 1 ]] ; then echo "Raw result from secondary:"; echo "$resultSec"; echo ; fi

# Parse the epoch time of both of those revisions.
resultPri=$(echo $resultPri | grep -o '<time>.*</time>' | sed 's/[<time>|<\/time>]//g' | awk -F\. '{print $1}')
resultSec=$(echo $resultSec | grep -o '<time>.*</time>' | sed 's/[<time>|<\/time>]//g' | awk -F\. '{print $1}')

if [[ $verbose -eq 1 ]] ; then echo "Stripped result from primary:   $resultPri" ; fi
if [[ $verbose -eq 1 ]] ; then echo "Stripped result from secondary: $resultSec" ; fi

# Used as sometimes the secondary updates a second after the primary in case of cert renewal
resultSec=$(echo "$resultSec + 2" | bc)

if [[ $resultSec -lt $resultPri ]] ; then
    echo "CRITICAL - Config has not been synced to secondary gateway."
    exit 2
else
    echo "OK - Config in sync."
    exit 0
fi

