#!/bin/bash
# https://github.com/onokatio/wayland-screenshot yad fork. GPL3
FILEDIR="$HOME"
OPTION=()

# Initialize gettext
TEXTDOMAIN=wayland-screenshot
TEXTDOMAINDIR=/usr/share/locale
export TEXTDOMAIN TEXTDOMAINDIR
ico=wayland-screenshot
values=$(yad \
  --title="$(gettext "Wayland Screenshot")" \
  --image=$ico --window-icon=$ico --name=$ico \
  --text="<b>$(gettext "Wayland Screenshot") $(gettext "Option")</b>" \
  --form \
  --field="$(gettext "Mode"):CB"  \
  --field="$(gettext "Include cursor"):CB"  \
  --field="$(gettext 'Time to wait'):NUM" \
  --field="$(gettext "Copy to"):CB"  \
  "$(gettext "All screen")!$(gettext "Specific window")!$(gettext "Specific area")" \
  "$(gettext "no")!$(gettext "yes")" \
  "" \
  "swappy!$(gettext "clipboard")!~/ws-*.png" \
  ) || exit 1

result=$?

mode=$(echo $values | cut -d '|' -f 1)
cursor=$(echo $values | cut -d '|' -f 2)
wait=$(echo $values | cut -d '|' -f 3)
clipboard=$(echo $values | cut -d '|' -f 4)

if [ "$result" -eq 1 ]; then      # select cancel
  echo "$(gettext "canceling")"
  exit
fi

if [ ! -z "$cursor" ] && [ "$cursor" == "yes" ]; then
  OPTION+="-c"
fi

if [ -z "$mode" ]; then       # select nothing
  echo "$(gettext "mode is null")"
  yad \
    --title="$(gettext "Wayland Screenshot")" \
    --width=200 \
    --text="$(gettext "Mode empty")" \
    --button="$(gettext "OK")":1
  exit
fi

if [ ! -z "$wait" ]; then
  sleep $wait
fi

if [ "$mode" == "$(gettext "All screen")" ]; then  # select All screen
  true
elif [ "$mode" == "$(gettext "Specific window")" ]; then  # select specify window
  GEO="$(swaymsg -t get_tree | jq -r '.. | select(.pid? and .visible?) | .rect | "\(.x),\(.y) \(.width)x\(.height)"' | slurp)"
elif [ "$mode" == "$(gettext "Specific area")" ]; then  # select specfy area
  GEO="$(slurp)"
else                         # error
  echo $mode
fi

if [ -z "$clipboard" ] || [ "$clipboard" == "clipboard" ]; then
  if [ -z "$GEO" ]; then
    grim $OPTION - | wl-copy
  else
    grim $OPTION -g "$GEO" - | wl-copy
  fi
elif [ -z "$clipboard" ] || [ "$clipboard" == "swappy" ]; then
  if [ -z "$GEO" ]; then
    grim $OPTION - | swappy -f -
  else
    grim $OPTION -g "$GEO" - | swappy -f -
  fi
else
  if [ -z "$GEO" ]; then
    grim $OPTION $FILEDIR/ws-$(date +%F_%H.%M.%S).png
  else
    grim $OPTION -g "$GEO" $FILEDIR/ws-$(date +%F_%H.%M.%S).png
  fi
fi
