#!/bin/bash

# dasscm_remote_update is intended for systems
# where a local dasscm installation is not possible
# but ssh and rsync is available.
# In this case,
# the files from the local repository checkout
# are updated to the current content.
# Use only, if a local dasscm installation is not possbile!

DIR="$1"

set -o errexit -o nounset

NAGIOS_OK=0
NAGIOS_WARN=1
NAGIOS_CRIT=2
NAGIOS_UNKNOWN=3

myexit()
{
    local RC="$1"
    shift
    local MESSAGE
    case "$RC" in
        $NAGIOS_OK)
            MESSAGE="OK: no modified files"
            ;;
        $NAGIOS_WARN)
            MESSAGE="Warning: changed: $*"
            ;;
        $NAGIOS_CRIT)
            MESSAGE="Critical: $*"
            ;;
        $NAGIOS_UNKNOWN|*)
            MESSAGE="an unknown error has occured: $*"
            ;;
    esac
    printf "$MESSAGE\n"
    exit $RC
}

if [ -z "$DIR" ]; then
    myexit $NAGIOS_CRIT "no file path given"
fi

if [ ! -d "$DIR" ]; then
    myexit $NAGIOS_CRIT "failed to access directory $DIR"
fi

LOCALCHANGES=`svn status "$DIR"`
if [ $? -ne 0 ]; then
    myexit $NAGIOS_CRIT "failed to retrieve local subversion info of directory  $DIR"
fi

DASSCM_RSYNC_OPTIONS=${DASSCM_RSYNC_OPTIONS:-""}
export DASSCM_RSYNC_OPTIONS="$DASSCM_RSYNC_OPTIONS --dry-run --checksum --out-format CHANGED:%n%L"
CHANGES=`dasscm_remote_update.sh "$@" | sed -n 's/CHANGED://p'`
if [ "$CHANGES" ]; then
    myexit $NAGIOS_WARN $CHANGES
else
    LOCALCHANGES=`svn status "$DIR"`
    if [ "$LOCALCHANGES" ]; then
        myexit $NAGIOS_WARN " (local) " $LOCALCHANGES
    else
        myexit $NAGIOS_OK
    fi
fi
