#!/bin/bash

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Get available disk space in mount point
#
# Returns:
#   The disk's available space in GB

set -Eeu -o pipefail

LABEL="${MNT:-/}"
BUTTON="${button:-}"
export LABEL BUTTON

get_disk_avail_gb() {
    read -r AVAIL_GB USED_PERCENT < <(df -h --output=avail,pcent "${LABEL}" | awk 'FNR == 2 {sub("%", "", $2); print $1, $2}')
}

get_disk_avail_gb

# The value turns to the warning or critical colour when this much (in percent) is used.
WARN=${warning_threshold:-$(xrescat i3xrocks.disk-capacity.warning_threshold 80)}
CRIT=${critical_threshold:-$(xrescat i3xrocks.disk-capacity.critical_threshold 90)}
if [[ "${USED_PERCENT}" =~ ^[0-9]+$ ]] && (( USED_PERCENT >= CRIT )); then
    VALUE_COLOR=${critical_color:-$(xrescat i3xrocks.critical.color "#BF616A")}
elif [[ "${USED_PERCENT}" =~ ^[0-9]+$ ]] && (( USED_PERCENT >= WARN )); then
    VALUE_COLOR=${warning_color:-$(xrescat i3xrocks.warning "#EBCB8B")}
else
    VALUE_COLOR=${color:-$(xrescat i3xrocks.value.color "#D8DEE9")}
fi
LABEL_ICON=${label_icon:-$(xrescat i3xrocks.label.disk D)}
LABEL_COLOR=${label_color:-$(xrescat i3xrocks.label.color "#7B8394")}
VALUE_FONT=${font:-$(xrescat i3xrocks.value.font "Source Code Pro Medium 13")}

echo "<span font_desc=\"${VALUE_FONT}\" color=\"${LABEL_COLOR}\">${LABEL_ICON}</span><span font_desc=\"${VALUE_FONT}\" color=\"${LABEL_COLOR}\"> $LABEL:</span> <span font_desc=\"${VALUE_FONT}\" color=\"${VALUE_COLOR}\">$AVAIL_GB</span>"

if [ "x${BUTTON}" == "x1" ]; then
    ACTION=$(xrescat i3xrocks.action.disk-capacity "/usr/bin/gnome-disks --class=floating_window")
    /usr/bin/i3-msg -q exec "$ACTION"
fi
