#!/usr/bin/env bash

set -uo pipefail
tmp_dir="/tmp/cliphist"
mkdir -p "$tmp_dir"
mode="${1:-}"
selection="${2:-}"

if [[ -n "$selection" ]]; then
    if [[ "$mode" == "clipboard" ]]; then
        id="${selection%% *}"
        printf '%s' "$id" | clipvault get | wl-copy
    elif [[ "$mode" == "notifications" ]]; then
        body="${selection#*— }"
        printf '%s' "$body" | wl-copy
    elif [[ "$mode" == "powermenu" ]]; then
        case "$ROFI_INFO" in
            lock)      swaylock ;;
            suspend)   systemctl suspend ;;
            reboot)    systemctl reboot ;;
            shutdown)  systemctl poweroff ;;
            logout)    loginctl terminate-session "${XDG_SESSION_ID-}" ;;
        esac
    else
        target_app=$(grep -rl "^Name=${selection}\$" /usr/share/applications/*.desktop 2>/dev/null | head -n1)
        if [[ -n "$target_app" ]]; then
            exec_cmd=$(awk -F= '/^Exec=/{print $2; exit}' "$target_app" | sed 's/%[uUfFck]//g')
            setsid $exec_cmd >/dev/null 2>&1 &
            disown
        fi
    fi
    exit 0
fi

case "$mode" in
    clipboard)
        find "$tmp_dir" -type f -mmin +30 -delete 2>/dev/null
        while IFS=$'\t' read -r id rest; do
            [[ "$id" =~ ^[0-9]+$ ]] || continue
            [[ "$rest" == *"meta http-equiv"* ]] && continue
            if [[ "$rest" == *"binary data"* ]]; then
                ext=""
                case "$rest" in
                    *jpeg*|*jpg*) ext="jpg" ;;
                    *png*)       ext="png" ;;
                    *bmp*)       ext="bmp" ;;
                    *)           continue ;;
                esac
                img="$tmp_dir/$id.$ext"
                [[ -s "$img" ]] || printf '%s\n' "$id" | clipvault get > "$img" 2>/dev/null
                [[ -s "$img" ]] && printf '%s [IMG]\0icon\x1f%s\n' "$id" "$img"
            else
                printf '%s %s\n' "$id" "$rest"
            fi
        done < <(clipvault list)
        ;;
    notifications)
        dunstctl history | jq -r '
            .data[0][] |
            "\(.appname.data): \(.summary.data) — \(.body.data)"
        '
        ;;
    internet|dev|media|games|system)
        case "$mode" in
            internet) category="Network" ;;
            dev)      category="Development" ;;
	    media)    category="AudioVideo" ;;
            games)    category="Game" ;;
            system)   category="System" ;;
        esac
        awk -v cat="$category" '
            BEGINFILE { name=""; icon=""; match_cat=0 }
            /^Categories=/ { if (index($0, cat)) match_cat=1 }
            /^Name=/  && name==""  { sub(/^Name=/, ""); name=$0 }
            /^Icon=/  && icon==""  { sub(/^Icon=/, ""); icon=$0 }
            ENDFILE {
                if (match_cat && name != "") {
                    if (icon != "") printf "%s\x00icon\x1f%s\n", name, icon
                    else printf "%s\n", name
                }
            }
        ' /usr/share/applications/*.desktop 2>/dev/null
        ;;
    powermenu)
        echo -e "\0markup-rows\x1ftrue"
        printf '%s\0info\x1flock\n'     "<span foreground=\"#88c0d0\"></span> lock"
        printf '%s\0info\x1fsuspend\n'  "<span foreground=\"#5e81ac\">󰤄</span> suspend"
        printf '%s\0info\x1freboot\n'   "<span foreground=\"#ebcb8b\"></span> reboot"
        printf '%s\0info\x1fshutdown\n' "<span foreground=\"#bf616a\">⏻</span> shutdown"
        printf '%s\0info\x1flogout\n'   "<span foreground=\"#b48ead\">󰗽</span> logout"
    ;;
esac
