#!/usr/bin/env bash
set -euo pipefail

notify() {
    notify-send "󰒓 System" "$1"
}

SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"

start_detached() {
    local command_name="$1"
    local unit_name="${command_name//[^[:alnum:]_.-]/-}"

    if command -v systemd-run >/dev/null 2>&1; then
        systemd-run --user --unit="$unit_name" --collect "$@" >/dev/null 2>&1 && return
    fi

    if command -v setsid >/dev/null 2>&1; then
        setsid -f "$@" >/dev/null 2>&1
    else
        "$@" >/dev/null 2>&1 &
    fi
}

restart_waybar() {
    local i

    pkill -x waybar >/dev/null 2>&1 || true

    for i in {1..20}; do
        pgrep -x waybar >/dev/null 2>&1 || break
        sleep 0.05
    done

    pgrep -x waybar >/dev/null 2>&1 && pkill -9 -x waybar >/dev/null 2>&1 || true
    start_detached waybar
}

choice="$(
    printf '%s\n' \
        "󰑓  Hyprland neu laden" \
        "󰌢  Waybar neu starten" \
        "󰏖  Paket Installation / Updates" \
        "󰗽  Bildschirm heller" \
        "󰗾  Bildschirm dunkler" \
        "󰍃  Session beenden" |
        wofi --dmenu --prompt "󰒓  System" --insensitive
)"

case "$choice" in
    *"Hyprland neu laden"*)
        hyprctl reload
        ;;
    *"Waybar neu starten"*)
        restart_waybar
        ;;
    *"Paket Installation / Updates"*)
        "$SCRIPT_DIR/package-manager.sh"
        ;;
    *"Bildschirm heller"*)
        if command -v brightnessctl >/dev/null 2>&1; then
            brightnessctl -e4 -n2 set 5%+
        else
            notify "brightnessctl ist nicht installiert."
        fi
        ;;
    *"Bildschirm dunkler"*)
        if command -v brightnessctl >/dev/null 2>&1; then
            brightnessctl -e4 -n2 set 5%-
        else
            notify "brightnessctl ist nicht installiert."
        fi
        ;;
    *"Session beenden"*)
        if command -v hyprshutdown >/dev/null 2>&1; then
            hyprshutdown
        else
            hyprctl dispatch exit
        fi
        ;;
esac
