#!/usr/bin/env bash

DFFILT="-x tmpfs -x devtmpfs -l"
FSFILT='\(/mnt/xstill\)'
MAIL=mail
MAIL_TO={{admin_email}}
if ! which $MAIL >&/dev/null; then
    MAIL=bsd-mailx
fi

FULL=$(df --output=pcent,avail,target,size $DFFILT | tail -n+2 | sed -e 's/^[ ]*//' -e 's/[ ][ ]*/,/g' | while read e; do
    PRC=$(echo $e | cut -f1 -d, | sed 's/%//')
    FREE=$(echo $e | cut -f2 -d,)
    FS=$(echo $e | cut -f3 -d,)
    SIZE=$(echo $e | cut -f4 -d,)
    if test -n "$FSFILT" && echo $FS | grep -q $FSFILT; then
        continue;
    fi
    unset WARN

    if [[ $PRC -gt 90 ]] && [[ $FREE -lt $((100 * 1024 * 1024)) ]]; then
        WARN=1
    fi
    if [[ $SIZE -gt $((32 * 1024 * 1024)) ]] && [[ $FREE -lt $((1024 * 1024)) ]]; then
        WARN=1
    fi

    if test -n "$WARN"; then
        echo $FS
    fi
done)

if test -n "$FULL"; then
    df -h $DFFILT | $MAIL -s "[DF:$(hostname)] Full: $FULL" ${MAIL_TO}
    exit 1
fi
