#!/usr/bin/env nix-shell
#!nix-shell -i bash -p libnotify -p swappy -p sway-contrib.grimshot -p util-linux -p wl-clipboard

# loosely inspired by reddit user u/dragobich
# - <https://www.reddit.com/r/hyprland/comments/12tal0f/comment/jh8j4sy/>

# give user this many seconds to respond before we expire the notification options
TIMEOUT=6
OUTDIR="$HOME/Pictures/Screenshots"
DATEFMT='%Y-%m-%d-%Hh%Mm%S'

notify() {
  local fullPath="$1"
  # replace $HOME with ~:
  local shortPath="~/${fullPath#$HOME/}"

  # --transient means that the notification won't appear in any notification centers (only on-screen)
  action=$(notify-send --icon="$fullPath" \
    --expire-time="$(( 1000*$TIMEOUT ))" --transient --urgency=normal \
    --action=Edit=Edit --action=CopyPath='Copy Path' \
    'Screenshot Captured' "Copied and saved to $shortPath")

  # fork to handle the action so that `delayedCancel` won't try to cancel us.
  handleAction "$action" "$fullPath" &
}

handleAction() {
  local action="$1"
  local fullPath="$2"
  case "$action" in
    Edit)
      # the save button in swappy seems to be broken (?),
      # but with --output-file it'll save on exit.
      swappy --file "$fullPath" --output-file "$fullPath"
      ;;
    CopyPath)
      wl-copy "$fullPath"
      ;;
    "")
      # action was dismissed
      ;;
    *)
      printf "sane-screenshot: unknown action %q\n" "$action" >&2
      ;;
  esac
}

delayedCancel() {
  # kill the given pid after the given timeout in seconds.
  # if the pid exits, then this function returns early.
  local pid="$1"
  waitpid --timeout="$2" "$pid" || \
    kill "$pid" || \
    true
}

name="$(date "+$DATEFMT").png"
dest="$OUTDIR/$name"

grimshot copy anything
wl-paste > "$dest"

notify "$dest" &
printf "screenshot copied and saved to %q\n" "$dest"
delayedCancel "$!" "$(( $TIMEOUT + 1 ))"
