#!/usr/bin/env bash
# shellcheck disable=all

# Copyright (C) 2021-2022 Zaharia Constantin <constantin.zaharia@progeek.ro>
# Copyright (C) 2021-2022 ProGeek <https://progeek.ro>
# SPDX-License-Identifier: GPL-3.0-or-later
#!/usr/bin/env bash

set -euo pipefail
LC_ALL=C
LC_NUMERIC=C

include () {
    [[ -f $1 ]] && source $1
}

include /var/local/machine/plugins/colors.sh

# config
max_usage=90
bar_width=50

# disk usage: ignore zfs, squashfs & tmpfs
mapfile -t dfs < <(df -H -x zfs -x squashfs -x tmpfs -x devtmpfs -x overlay -x shm --output=target,pcent,size | tail -n+2)
printf "\nDisk usage:\n"

for line in "${dfs[@]}"; do
    # get disk usage
    usage=$(echo "$line" | awk '{print $2}' | sed 's/%//')
    used_width=$((($usage*$bar_width)/100))

    # color is green if usage < max_usage, else red
    if [ "${usage}" -ge "${max_usage}" ]; then
        color=$RED
    else
        color=$GRN
    fi

    # print green/red bar until used_width
    bar="[${color}"
    for ((i=0; i<$used_width; i++)); do
        bar+="="
    done

    # print dimmmed bar until end
    bar+="${GRY}${DIM}"
    for ((i=$used_width; i<$bar_width; i++)); do
        bar+="="
    done

    bar+="${DEF}]"

    # print usage line & bar
    echo "${line}" | awk '{ printf("%-31s%+3s used out of %+4s\n", $1, $2, $3); }' | sed -e 's/^/  /'
    echo -e "${bar}" | sed -e 's/^/  /'
done