#!/bin/bash

###################################################
## shut down pc and break instantwm restart loop ##
###################################################

# Prevent overlapping instances with lockfile
exec 200>/tmp/instantshutdown.lock 2>/dev/null || true
if command -v flock >/dev/null 2>&1; then
    flock -n 200 || {
        echo "instantshutdown already running"
        exit 0
    }
fi

if [ -n "$1" ]; then
    answer="$1"
else
    # '{color icon=name} label' items, same convention as instantstartmenu
    MENUITEMS='{red icon=cancel} cancel
{red icon=power} shutdown
{blue icon=logout} logout
{blue icon=restart} reboot
{blue icon=lock} lock screen
{blue icon=sleep} suspend'
    if [ "$XDG_SESSION_TYPE" = wayland ] || [ -n "$WAYLAND_DISPLAY" ]; then
        echo "wayland detected, not offering restart wm"
    else
        # restarting instantwm is an X11 thing
        MENUITEMS="$MENUITEMS
{blue icon=refresh} restart wm"
    fi
    answer="$(echo "$MENUITEMS" | ins menu choice "shutdown menu" 2>/dev/null)"
fi

# Strip markup and normalize case for reliable matching
clean_answer="$(echo "$answer" | sed -E 's/^\{[^{}]*\} //; s/^[[:space:]]*//; s/[[:space:]]*$//' | tr '[:upper:]' '[:lower:]')"

# if there are apps open, ask for confirmation
zconfirm() {
    if command -v wmctrl >/dev/null 2>&1; then
        OPEN_APPS="$(wmctrl -l 2>/dev/null | grep -v -i -E 'instantbar|desktop|scratchpad' || true)"
        if [ -n "$OPEN_APPS" ]; then
            echo "running applications found"
            if ins menu confirm "there are apps running, sure you want to $1?"; then
                echo "yes"
                return 0
            else
                echo "no"
                exit 0
            fi
        fi
    fi
    echo "no running applications found"
}

prepareshutdown() {
    # save current brightness
    touch /tmp/shuttingdown
    if command -v brightnessctl >/dev/null 2>&1; then
        CURBRIGHT="$(brightnessctl -m 2>/dev/null | awk -F, '{print $4}' | tr -d '%' || true)"
        if [ -n "$CURBRIGHT" ]; then
            iconf savebright "$CURBRIGHT" 2>/dev/null || true
        fi
    fi

    if command -v instantruntimedir >/dev/null 2>&1; then
        rm -f "$(instantruntimedir)/instantosrunning" 2>/dev/null || true
    fi
    # these keep causing stop jobs
    pkill -f clipnotify 2>/dev/null || true
    pkill -f clipmenud 2>/dev/null || true
}

case "$clean_answer" in
    shut*|*power*)
        zconfirm "shutdown"
        prepareshutdown
        sleep 0.4
        if command -v systemctl >/dev/null 2>&1; then
            systemctl poweroff || shutdown -h now || shutdown now
        else
            # needs root on Artix / non-systemd
            instantsudo poweroff || poweroff
        fi
        ;;
    reb*|*restart*)
        zconfirm "reboot"
        prepareshutdown
        sleep 0.4
        if command -v systemctl >/dev/null 2>&1; then
            systemctl reboot || reboot
        else
            instantsudo reboot || reboot
        fi
        ;;
    log*|*logout*|*sign*out*)
        zconfirm "sign out"
        if command -v instantruntimedir >/dev/null 2>&1; then
            rm -f "$(instantruntimedir)/instantosrunning" 2>/dev/null || true
        fi
        sleep 0.4
        if command -v loginctl >/dev/null 2>&1; then
            loginctl terminate-session self 2>/dev/null || pkill -u "$USER" -x instantwm || kill -9 -1
        else
            pkill -u "$USER" -x instantwm || kill -9 -1
        fi
        ;;
    loc*|*lock*)
        instantutils open lockscreen
        ;;
    sus*|*sleep*)
        if command -v systemctl >/dev/null 2>&1; then
            systemctl suspend
        fi
        export NOILOCKPASSWORD="true"
        instantutils open lockscreen
        ;;
    res*|*wm*)
        pkill -x instantwm
        ;;
    cancel*|"")
        echo "canceled"
        ;;
    *)
        echo "unknown option: $answer"
        ;;
esac
