#!/bin/bash

# Example notifier script -- lowers screen brightness, then waits to be killed
# and restores previous brightness on exit.

## CONFIGURATION ##############################################################

# Brightness will be lowered to this value.
min_brightness=0

# If you have a driver without RandR backlight property (e.g. radeon), set this
# to use the sysfs interface and create a .conf file in /etc/tmpfiles.d/
# containing the following line to make the sysfs file writable for group
# "users":
#
#     m /sys/class/backlight/acpi_video0/brightness 0664 root users - -
#
#sysfs_path=/sys/class/backlight/acpi_video0/brightness

# Time to sleep (in seconds) between increments when using sysfs. If unset or
# empty, fading is disabled.
fade_step_time=0.05

###############################################################################

get_brightness() {
    brightnessctl get  # Get current brightness level
}

set_brightness() {
    brightnessctl set $1  # Set brightness to the specified percentage
}

fade_brightness() {
    local current_brightness=$(get_brightness)
    local target_brightness=$1

    if [[ $current_brightness -eq $target_brightness ]]; then
        return  # No need to change brightness
    fi

    local step
    local fade_steps=$(( (current_brightness - target_brightness) / 1000 ))
    local increment=1000

    for (( step=0; step<fade_steps; step++ )); do
        if [[ ! -e /tmp/asleepin ]]; then
          exit 0
        fi
        local new_brightness=$(( current_brightness - increment * (step + 1) ))
        set_brightness $new_brightness
        sleep $fade_step_time
    done

    set_brightness $target_brightness  # Ensure we set to the exact target
}

trap 'exit 0' TERM INT
trap "set_brightness $(get_brightness); kill %%" EXIT
fade_brightness $min_brightness
while [ -e /tmp/asleepin ]; do
    sleep 0.5
done
exit 0
#wait

