#!/usr/bin/env bash
# ---------------------------------------------------------------------------
#  Screenshots with maim.  usage: screenshot full|area|window [--clip-only]
#  Images land in ~/Pictures/Screenshots and are copied to the clipboard.
# ---------------------------------------------------------------------------
set -uo pipefail

DIR="${SCREENSHOT_DIR:-$(xdg-user-dir PICTURES 2>/dev/null || echo "$HOME/Pictures")/Screenshots}"
STAMP="$(date +%Y-%m-%d_%H-%M-%S)"
FILE="$DIR/screenshot_$STAMP.png"
MODE="${1:-full}"
CLIP_ONLY=0
[[ "${2:-}" == "--clip-only" ]] && CLIP_ONLY=1

command -v maim >/dev/null || { echo "maim not installed" >&2; exit 1; }
mkdir -p "$DIR"

# Selection colour = Catppuccin mauve (maim wants floats 0-1)
SELECT_COLOR="0.776,0.627,0.965,0.5"

case "$MODE" in
  full)
    maim --hidecursor --quality 10 "$FILE" ;;
  area)
    maim --select --hidecursor --quality 10 --color="$SELECT_COLOR" \
         --bordersize=2 --nodrag "$FILE" ;;
  window)
    maim --window "$(xdotool getactivewindow)" --hidecursor --quality 10 "$FILE" ;;
  *)
    echo "usage: screenshot full|area|window [--clip-only]" >&2; exit 2 ;;
esac

# maim exits non-zero when the user cancels an area selection with Escape.
if [[ ! -s "$FILE" ]]; then
  rm -f "$FILE"
  exit 0
fi

command -v xclip >/dev/null && xclip -selection clipboard -t image/png -i "$FILE"

if [[ "$CLIP_ONLY" == "1" ]]; then
  rm -f "$FILE"
  command -v dunstify >/dev/null && \
    dunstify -a screenshot -i camera-photo "Screenshot" "Copied to clipboard"
  exit 0
fi

command -v dunstify >/dev/null && \
  dunstify -a screenshot -i "$FILE" "Screenshot saved" "$(basename "$FILE")\nCopied to clipboard"
