#!/bin/sh

die() {
    # When run from WM, $TERM appear to be set to "linux"
    # TODO: find a less brittle solution
    [ "$TERM" = "linux" ] && notify-send "$@" || echo "$@"
    exit 1
}

check_exists() {
    which "$1" > /dev/null 2>&1 || die "$1 doesn't appear to be installed"
}

if [ -z "$1" ]; then
    NAME="shot_$(date '+%Y%m%d%H%M%S').png"
else
    NAME="$1"
fi

SCREEN_DIR="$HOME/img/screenshots"
mkdir -p "$SCREEN_DIR"
# Let's try to detect Wayland running
if [ -z "$WAYLAND_DISPLAY" ]; then
    check_exists "maim"
    maim -s "$SCREEN_DIR/$NAME"
    # Fail silently if xsel isn't installed, the clipboard feature isn't critical
    echo "$SCREEN_DIR/$NAME" | xsel -b -i > /dev/null 2>&1
else
    check_exists "grim"
    check_exists "slop"
    slop | awk -F '[x+]' '{printf "%s,%s %sx%s",$3,$4,$1,$2}' | grim -g - "$SCREEN_DIR/$NAME"
    # Same as xsel
    wl-copy -n "$SCREEN_DIR/$NAME" > /dev/null 2>&1
fi