#!/usr/bin/env sh
# Take a screenshot on wayland
# By default takes a screenshot of the whole desktop
# If 'region' or 'area' command is passed in will allow selecting a region to screenshot.
# Example: `screenshot region`

TIME="$(date +%Y-%m-%d-%H-%M-%S)"
readonly TIME
readonly TMPSCREENSHOTDIR="$HOME/.cache/screenshot"
readonly TMPIMGPATH="$TMPSCREENSHOTDIR/img-$TIME.png"

FULLSCREEN=true

if [ "$1" = "area" ] || [ "$1" = "region" ]; then
    FULLSCREEN=false
fi

main() {
    prepare_cache
    take_screenshot "$FULLSCREEN"
    if [ -n "$SCREENSHOT_POSTPROCESS" ]; then
        eval "$SCREENSHOT_POSTPROCESS"
    else
        postprocess
    fi
}

prepare_cache() {
    if [ ! -d "$TMPSCREENSHOTDIR" ]; then
        mkdir -p "$TMPSCREENSHOTDIR"
    fi
}

take_screenshot() {
    if $1; then
        grim "$TMPIMGPATH"
    else
        grim -g "$(slurp)" "$TMPIMGPATH"
    fi
}

postprocess() {
    notify-send -i "$TMPIMGPATH" "Screenshot taken" "$TMPIMGPATH"
    echo "$TMPIMGPATH" | wl-copy
    echo "$TMPIMGPATH"
}

main "$@"