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

screenshot_dir="${XDG_PICTURES_DIR:-$HOME/Pictures}/Screenshots"

notify() {
    notify-send "󰸉 Screenshot" "$1"
}

require_cmd() {
    local cmd="$1"

    if ! command -v "$cmd" >/dev/null 2>&1; then
        notify "$cmd ist nicht installiert."
        exit 1
    fi
}

filename() {
    date +%Y-%m-%d_%H-%M-%S.png
}

take_hyprshot() {
    local mode="$1"
    local name="$2"

    require_cmd hyprshot
    mkdir -p "$screenshot_dir"
    hyprshot -m "$mode" -o "$screenshot_dir" -f "$name" -s
    printf '%s/%s\n' "$screenshot_dir" "$name"
}

annotate_region() {
    local name path

    require_cmd satty
    name="$(filename)"
    path="$(take_hyprshot region "$name")"
    satty --filename "$path" --output-filename "$path"
}

quick_region() {
    local name

    name="$(filename)"
    take_hyprshot region "$name" >/dev/null
    notify "Bereich gespeichert."
}

quick_window() {
    local name

    name="$(filename)"
    take_hyprshot window "$name" >/dev/null
    notify "Fenster gespeichert."
}

quick_output() {
    local name

    name="$(filename)"
    take_hyprshot output "$name" >/dev/null
    notify "Bildschirm gespeichert."
}

copy_region() {
    require_cmd hyprshot
    hyprshot -m region --clipboard-only -s
    notify "Bereich in die Zwischenablage kopiert."
}

show_menu() {
    require_cmd wofi

    local choice
    choice="$(
        printf '%s\n' \
            "󰹑  Bereich markieren" \
            "󰸉  Bereich speichern" \
            "󰍹  Fenster speichern" \
            "󰹑  Bildschirm speichern" \
            "󰅌  Bereich kopieren" |
            wofi --dmenu --prompt "󰸉  Screenshot" --insensitive
    )"

    case "$choice" in
        *"Bereich markieren"*)
            annotate_region
            ;;
        *"Bereich speichern"*)
            quick_region
            ;;
        *"Fenster speichern"*)
            quick_window
            ;;
        *"Bildschirm speichern"*)
            quick_output
            ;;
        *"Bereich kopieren"*)
            copy_region
            ;;
    esac
}

case "${1:-menu}" in
    annotate-region)
        annotate_region
        ;;
    region)
        quick_region
        ;;
    window)
        quick_window
        ;;
    output)
        quick_output
        ;;
    copy-region)
        copy_region
        ;;
    menu)
        show_menu
        ;;
    *)
        notify "Unbekannter Screenshot-Modus: $1"
        exit 2
        ;;
esac
