#!/bin/bash

threshold=${1:-96}

PIDFILE="${XDG_RUNTIME_DIR:-/tmp}/diskspace-monitor.$USER.pid"

[ -e "$PIDFILE" ] && echo 'Already running.' && exit 0

echo "$$" > "$PIDFILE"
trap "rm $PIDFILE 2>/dev/null || true" EXIT TERM KILL

# bash+gettext translated strings
WARNING_TITLE=$"You are running low on disk space"
WARNING_BODY=$"Your %s disk partition is over %s full. Make some room there, will you"'!'

while true; do
  df --local --exclude-type tmpfs --exclude-type devtmpfs --exclude-type rootfs | 
  tail -n +2 | 
  while read _1 _2 _3 _4 percent partition; do 
    [ ${percent::-1} -lt $threshold ] && continue
    if command -v notify-send >/dev/null; then
      notify-send --urgency=critical \
                  --expire-time=0 \
                  --icon=gdu-warning \
                  --category=device \
                  "$WARNING_TITLE" \
                  "$(printf "$WARNING_BODY" "<b>$partition</b>" "<b>$percent</b>")"
    else
      zenity  --notification \
              --timeout 0 \
              --window-icon gdu-warning \
              --text "$WARNING_TITLE. $WARNING_BODY" &
    fi
    zenity  --warning \
            --title "$WARNING_TITLE" \
            --text "$(printf "$WARNING_BODY" "<b>$partition</b>" "<b>$percent</b>")"
  done
  sleep $((4*3600))
done
