#!/bin/bash

# i3exit
#
# Provide simple arguments for various locking and power related tasks.

# with openrc use loginctl
[[ $(cat /proc/1/comm) == "systemd" ]] && logind=systemctl || logind=loginctl

LOCK_SCREEN_BLUR=${LOCK_SCREEN_BLUR:-false}
LOCK_SCREEN_COLOR=${LOCK_SCREEN_COLOR:-29414f}

_lock() {
    i3lock -c "$LOCK_SCREEN_COLOR"
}

_unlock() {
    pkill -u "$USER" -f "i3lock -(c|i) "
}

lock() {
    local screen=/tmp/screenshot.png blurred=/tmp/screenshotblur.png

    _lock # Lock immediately

    if $LOCK_SCREEN_BLUR; then
        # Take screenshot and blur it
        scrot -q 100 $screen || return 1 # Larger file size, but faster
        convert -scale 10% -blur 0x1.25 -resize 1000% $screen $blurred || return 1
        rm $screen

        # Now try to replace the solid color with the blurred image.
        _unlock
        i3lock -i $blurred || _lock
    fi

    # Add a small delay to prevent possible race conditions with suspend
    sleep 1
}

case "$1" in
    lock)
        lock; echo $?
        ;;
    logout)
        i3-msg exit
        ;;
    switch_user)
        dm-tool switch-to-greeter
        ;;
    suspend)
        lock && $logind suspend
        ;;
    hibernate)
        lock && $logind hibernate
        ;;
    reboot)
        $logind reboot
        ;;
    shutdown)
        $logind poweroff
        ;;
    commands)
        echo "lock,logout,switch_user,suspend,hibernate,reboot,shutdown"
        ;;
    help)
        cmds="$($0 commands)"
        echo "Usage: $0 ${cmds//\,/\, }"
        ;;
    *)
        echo "== ! i3exit: missing or invalid argument ! =="
        $0 help
        exit 2
        ;;
esac

exit 0
