#!/bin/bash
#wayland screenshot by dimkr

if [ "$1" = "full" ]; then
	FULL=1
elif [ "$1" = "region" ]; then
	FULL=0
elif command -v slurp > /dev/null; then
	yad --title=" " --window-icon=gtk-fullscreen --layer=overlay --edge=bottom --button="Whole screen"\!edit-select-all-symbolic:2 --button="Select region"\!edit-select-symbolic:3 --button=gtk-cancel:1
	RET=$?
	[ $RET -eq 2 -o $RET -eq 3 ] || exit
	FULL=1
	[ $RET -eq 3 ] && FULL=0
else
	FULL=1
fi

if [ $FULL -eq 0 ]; then
	GEOM="`slurp`"
	[ -z "$GEOM" ] && exit
else
	OUTPUTS="`wlr-randr | grep -m 2 -v '^ ' | cut -f 1 -d ' ' | tr '\n' ' ' | sed 's/ $//'`"
	OUTPUT="${OUTPUTS%% *}"
	[ -z "$OUTPUT" ] && exit
	if [ "$OUTPUT" != "$OUTPUTS" ]; then
		OUTPUT="`slurp -p -f %o`"
		[ -z "$OUTPUT" ] && exit
	fi
fi

VIDEO=0
if command -v wf-recorder > /dev/null; then
	yad --title=" " --window-icon=gtk-fullscreen --layer=overlay --edge=bottom --button=Image\!camera-photo-symbolic:2 --button=Video\!camera-video-symbolic:3 --button=gtk-cancel:1
	RET=$?
	[ $RET -eq 2 -o $RET -eq 3 ] || exit
	[ $RET -eq 3 ] && VIDEO=1
fi

if [ $VIDEO -eq 0 ]; then
	if command -v wl-copy > /dev/null; then
		yad --title=" " --window-icon=gtk-fullscreen --layer=overlay --edge=bottom --button="Copy to clipboard"\!edit-copy-symbolic:2 --button="Save to file"\!document-save-as-symbolic:3 --button=gtk-cancel:1
		RET=$?
		if [ $RET -eq 2 ]; then
			if [ $FULL -eq 0 ]; then
				grim -g "$GEOM" - | wl-copy -t image/png
			else
				grim -o "$OUTPUT" - | wl-copy -t image/png
			fi
			exit
		fi
		[ $RET -ne 3 ] && exit
	fi

	DST=`yad --title=" " --window-icon=gtk-fullscreen --layer=overlay --edge=bottom --file --save --confirm-overwrite --filename=screenshot.png`
	[ -z "$DST" ] && exit

	if [ $FULL -eq 0 ]; then
		grim -g "$GEOM" "$DST"
	else
		grim -o "$OUTPUT" "$DST"
	fi
else
	DST=`yad --title=" " --window-icon=gtk-fullscreen --layer=overlay --edge=bottom --file --save --confirm-overwrite --filename=recording.mkv`
	[ -z "$DST" ] && exit

	if [ $FULL -eq 0 ]; then
		wf-recorder -g "$GEOM" -f "$DST" &
	else
		wf-recorder -o "$OUTPUT" -f "$DST" &
	fi
	PID=$!

	yad --title=" " --window-icon=gtk-fullscreen --layer=overlay --edge=bottomright --no-focus --button="Stop recording"\!gtk-stop
	kill -INT $PID
	while kill -0 $PID 2>/dev/null; do
		sleep 0.5
	done
fi

exec xdg-open "$DST"
