#!/bin/bash

warn=15
crit=10

set -e
while getopts ":H:u:i:c:w:" opt; do
    case $opt in
    H ) # Specify hostname
        HSTNAME="$OPTARG" # Hostname reserved keyword
        ;;
    u ) # Specify username
        user="$OPTARG"
        ;;
    i ) # Specify keyfile
        keyFile="$OPTARG"
        ;;
    c ) # Specify crit value for amperage and wattage
        crit="$OPTARG"
        ;;
    w ) # Specify warn value for amperage and wattage
        warn="$OPTARG"
        ;;
    ? )
        echo "invalid option $OPTARG. script usage: $(basename $0) [-H hostname] [-u username] [-i keyFile] [-w pctFreeWarn] [-c pctFreeCrit]" >&2
        exit 3
        ;;
    esac
done

# Grab result from SSH
result=$(ssh -i $keyFile -o StrictHostKeyChecking=no $user@$HSTNAME "df /tmp")
if ! [ "$result" ] ; then
    echo "UNKN - Unable to retrieve disk usage from $HSTNAME"
    exit 3
fi

# Parsed used and available values for /tmp via awk
diskUsed=$(echo "${result}" | awk 'NR==1 {for (i=1; i<NF; i++) {if ($i=="Used") {title=i;}}} NR==2 {print $title;}')
diskFree=$(echo "${result}" | awk 'NR==1 {for (i=1; i<NF; i++) {if ($i=="Available") {title=i;}}} NR==2 {print $title;}')


# Calculate total percent free
diskTotal=$(echo "$diskUsed+$diskFree" | bc)
diskPctFree=$(echo "scale=1;($diskFree*100)/$diskTotal" | bc -l)
diskPctUsed=$(echo "scale=1;($diskUsed*100)/$diskTotal" | bc -l)

# Standard handling
if (($(echo "$diskPctFree>$warn" | bc -l)==1)) ; then
    echo "OK - Disk usage: ${diskUsed}K/${diskTotal}K; $diskPctFree% available.|disk_used=$diskPctUsed%"
    exit 0
elif (($(echo "$diskPctFree<$crit" | bc -l)==1)) ; then
    echo "CRIT - Disk usage: ${diskUsed}K/${diskTotal}K; $diskPctFree% available.|disk_used=$diskPctUsed%"
    exit 2
elif (($(echo "$diskPctFree<$warn" | bc -l)==1)) ; then
    echo "WARN - Disk usage: ${diskUsed}K/${diskTotal}K; $diskPctFree% available.|disk_used=$diskPctUsed%"
    exit 1
else
    echo "UNKN - Disk usage: ${diskUsed}K/${diskTotal}K; $diskPctFree% available.|disk_used=$diskPctUsed%"
    exit 3
fi
