#!/bin/bash

function usage {
    cat << EOF
usage: $0 options

    Check the disk space available for the configured directories

OPTIONS:
    -h              Show this message
EOF
}

function parseArguments {
    while getopts "h?" opt; do
        case "$opt" in
            h|\?)
                usage
                exit 0
                ;;
        esac
    done
}

function parseConfiguration {
    if [ -f $1 ]; then
        DISKCHECKDIRS=`grep ^[[:blank:]]*spacecheck_dirs $1 | sed -e "s/.*=[[:blank:]]*//"`
        DISKCHECKALERT=`grep ^[[:blank:]]*spacecheck_free_alert $1 | sed -e "s/.*=[[:blank:]]*//"`
        DISKTHRESHOLD=`grep ^[[:blank:]]*spacecheck_free_critical $1 | sed -e "s/.*=[[:blank:]]*//"`
    fi

    if [ "$DISKCHECKDIRS" = "" ]; then
        DISKCHECKDIRS="/var/spacewalk /var/cache /srv"
    fi

    if [ "$DISKCHECKALERT" = "" ]; then
        DISKCHECKALERT=90
    fi

    if [ "$DISKTHRESHOLD" = "" ]; then
        DISKTHRESHOLD=95
    fi
}

function ensureSpacewalkRunning {
    systemctl status spacewalk.target > /dev/null 2>&1
    if [ $? != 0 ]; then
        echo  "DISKCHECK: spacewalk services are not running - skipping disk check."
        exit 0
    fi
}

function updateSeverity {
    if [ $1 -gt $CHECKSEVERITY ]; then
        CHECKSEVERITY=$1
    fi
}

# Main script

CHECKSEVERITY=0

ensureSpacewalkRunning

parseArguments "$@"
parseConfiguration /etc/rhn/rhn.conf

for DIR in $DISKCHECKDIRS
do
    if [ ! -d $DIR ]; then
        updateSeverity 1
        continue
    fi

    USEDSPACE=`df -PH $DIR | tail -1 | awk '{print $5}' | sed -e"s/\%//"`
    if [ $USEDSPACE -gt $DISKTHRESHOLD ]; then
        updateSeverity 3
    elif [ $USEDSPACE -gt $DISKCHECKALERT ]; then
        updateSeverity 2
    fi
done

exit $CHECKSEVERITY
