#!/bin/bash
#
# Nagios plugin to check Git repository status
#
# Author : Benjamin Renard <brenard@easter-eggs.com>
# Source : https://gitlab.easter-eggs.com/ee/ee-monitoring/
#

GIT_ROOT=/srv/common
GIT_REMOTE=origin
DEBUG=0
CHECK_REMOTE=0
HIDE_CHANGES=0
FULL_DIFF=0

function usage() {
    echo "Usage : $0 -g [directory] [-c|-r remote] [-d]
    -g [directory]    Specify Git directory (default : $GIT_ROOT)
    -c        Check Git remote state
    -r [remote]    Specify Git remote to check (default : $GIT_REMOTE)
    -H        Hide detected changes
    -F        Show full diff in case of changes detected (default: short)
    -d        Enable debug mode"
}

while getopts "g:r:cdFHh-:" OPTION
do
    case "$OPTION" in
        c)
            CHECK_REMOTE=1
        ;;
        g)
            GIT_ROOT="${OPTARG}"
        ;;
        r)
            CHECK_REMOTE=1
            GIT_REMOTE="${OPTARG}"
        ;;
        d)
            DEBUG=1
        ;;
        H)
            HIDE_CHANGES=1
        ;;
        F)
            FULL_DIFF=1
        ;;
        h)
            usage
            exit 0
        ;;
        *)
            echo "Invalid parameter -$OPTION"
            echo
            usage
            exit 1
        ;;
    esac
done

[ ! -d "$GIT_ROOT" ] && echo "UNKNOWN : Directory ${GIT_ROOT} does not exists !" && exit 3

STATUS=$( git -C ${GIT_ROOT} status -s . 2>&1 )
res=$?
[ $DEBUG -eq 1 ] && echo -e "Status (return $res): $STATUS"

if [ $res -ne 0 ]
then
    echo "UNKNOWN : Fail to retreive git status (return code : $res)"
    echo -e "$STATUS"
    exit 3
elif [ -n "$STATUS" ]
then
    echo "WARNING : Git directory $( hostname ):${GIT_ROOT} not clean"
    if [ $FULL_DIFF -eq 1 ]
    then
        git -C ${GIT_ROOT} diff .
    elif [ $HIDE_CHANGES -ne 1 ]
    then
        echo -e "$STATUS"
    fi
    exit 1
elif [ $CHECK_REMOTE -eq 1 ]
then
    # Check remote exists
    [ $DEBUG -eq 1 ] && echo -n "Check remote '$GIT_REMOTE' exist : "
    git -C ${GIT_ROOT} remote show "$GIT_REMOTE" > /dev/null 2>&1
    res=$?
    [ $DEBUG -eq 1 ] && echo "done. (Return $res)"

    if [ $res -ne 0 ]
    then
        echo "UNKNOWN : Unkown remote '$GIT_REMOTE'"
        exit 3
    fi

    [ $DEBUG -eq 1 ] && echo -n "Fecth : "
    git -C ${GIT_ROOT} fetch "$GIT_REMOTE" > /dev/null 2>&1
    res=$?
    [ $DEBUG -eq 1 ] && echo "done. (Return $res)"

    if [ $res -ne 0 ]
    then
        echo "UNKNOWN : Error fetching remote"
        exit 3
    fi

    HEAD="$( git -C ${GIT_ROOT} show HEAD|grep ^commit )"
    [ $DEBUG -eq 1 ] && echo "Local : $HEAD"

    ORIGIN="$( git -C ${GIT_ROOT} show origin|grep ^commit )"
    [ $DEBUG -eq 1 ] && echo "Remote : $ORIGIN"
    
    if [ "$HEAD" != "$ORIGIN" ]
    then
        echo "CRITICAL : Git config not uptodate"
        exit 2
    fi
fi
echo "OK"
exit 0

# vim:ts=4:sw=4:noet