#!/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 {
    local conf="$1"

    if [ -z "${DISKCHECKDIRS}" ] && [ -f "$conf" ]; then
        DISKCHECKDIRS=$(grep '^[[:blank:]]*spacecheck_dirs' "$conf" | sed -e 's/.*=[[:blank:]]*//')
    fi
    if [ -z "${DISKCHECKALERT}" ] && [ -f "$conf" ]; then
        DISKCHECKALERT=$(grep '^[[:blank:]]*spacecheck_free_alert' "$conf" | sed -e 's/.*=[[:blank:]]*//')
    fi
    if [ -z "${DISKTHRESHOLD}" ] && [ -f "$conf" ]; then
        DISKTHRESHOLD=$(grep '^[[:blank:]]*spacecheck_free_critical' "$conf" | sed -e 's/.*=[[:blank:]]*//')
    fi

    [ -z "${DISKCHECKDIRS}" ] && DISKCHECKDIRS="/var/spacewalk /var/cache /srv"
    [ -z "${DISKCHECKALERT}" ] && DISKCHECKALERT=90
    [ -z "${DISKTHRESHOLD}" ]  && DISKTHRESHOLD=95

    # Strip surrounding quotes that may have been introduced via env or rhn.conf.
    DISKCHECKDIRS="${DISKCHECKDIRS%\"}"; DISKCHECKDIRS="${DISKCHECKDIRS#\"}"
    DISKCHECKDIRS="${DISKCHECKDIRS%\'}"; DISKCHECKDIRS="${DISKCHECKDIRS#\'}"

    # Split into a bash array for safe iteration.
    read -ra DISKCHECKDIRS_ARR <<< "$DISKCHECKDIRS"
}

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_ARR[@]}"; do
    if [ ! -d "$DIR" ]; then
        echo "DISKCHECK: Directory $DIR does not exist"
        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
