#!/bin/sh

export DISPLAY=:0
export DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/1000/bus"

# Battery percentage at which to dunstify
WARNING_LEVEL=25
BATTERY_DISCHARGING=`acpi -b | grep "Battery 0" | grep -c "Discharging"`
BATTERY_LEVEL=`acpi -b | grep "Battery 0" | grep -P -o '[0-9]+(?=%)'`
CRITICAL_LEVEL=13
# Use two files to store whether we've shown a notification or not (to prevent multiple notifications)
LOW_FILE=/tmp/batterylow
FULL_FILE=/tmp/batteryfull
EMPTY_FILE=/tmp/batteryempty

# Reset notifications if the computer is charging/discharging
if [ $BATTERY_DISCHARGING -eq 1 ] && [ -f $FULL_FILE ]; then
    rm $FULL_FILE
elif [ $BATTERY_DISCHARGING -eq 0 ] && [ -f $LOW_FILE ]; then
    rm $LOW_FILE
    rm $EMPTY_FILE
fi

# If the battery is charging and is full (and has not shown notification yet)
if [ $BATTERY_LEVEL -gt 95 ] && [ $BATTERY_DISCHARGING -eq 0 ] && [ ! -f $FULL_FILE ]; then
    dunstify "Battery Charged" "Battery is fully charged." -i ~/.config/dunst/icons/battery-charged.png -r 9991
    touch $FULL_FILE
# If the battery is low and is not charging (and has not shown notification yet)
elif [ $BATTERY_LEVEL -le $WARNING_LEVEL ] && [ $BATTERY_DISCHARGING -eq 1 ] && [ ! -f $LOW_FILE ]; then

    dunstify "Low Battery" "${BATTERY_LEVEL}% of battery remaining." -i ~/.config/dunst/icons/battery-low.png -u critical -r 9991
    touch $LOW_FILE
# Critical level
elif [ $BATTERY_LEVEL -le $CRITICAL_LEVEL ] && [ $BATTERY_DISCHARGING -eq 1 ] && [ ! -f $EMPTY_FILE ]; then

    dunstify "Battery Critical" "${BATTERY_LEVEL}% of battery remaining." -i ~/.config/dunst/icons/battery-critical.png -u critical -r 9991
    touch $EMPTY_FILE
    paplay ~/.config/dunst/alet1.mp3
fi
