#!/usr/bin/env bash
# cap -- screenshot a window or screen
#
# Uses GNOME Shell's screenshot functionality if available, so that window
# shadows get captured correctly (with PNG transparency).

. lib.bash || exit

set -u

has_gnome_shell() {
	have busctl && busctl --user --acquired | grep -qw "^org\.gnome\.Shell"
}

usage() {
	echo "Usage: $progname [-auw] [-l SEC]"
	echo ""
	echo_opt "-w"		"capture active window"
	echo_opt "-a"		"capture selected area"
	echo_opt "-l SEC"	"delay before capture"
	echo_opt "-u"		"upload image after capture"
}

basedir=$(systemd-path user-pictures || echo ~/Pictures)
file=$basedir/Screenshots/$(date +%Y-%m-%d.%H%M%S).${HOSTNAME%%.*}.png

opt_window=0		# capture the active window only
opt_area=0
opt_upload=0
opt_delay=0		# delay between area select and capture

while getopts :al:uw OPT; do
	case $OPT in
	a) opt_area=1;;
	l) opt_delay=$OPTARG;;
	u) opt_upload=1;;
	w) opt_window=1;;
	*) lib:die_getopts;;
	esac
done; shift $((OPTIND-1))

if (( $# )); then
	vdie "excess arguments"
fi

if [[ ! $opt_delay =~ ^[0-9]+$ ]]; then
	vdie "invalid -l value"
fi

if (( opt_area && opt_window )); then
	vdie "-a and -w cannot be used together"
fi

if have gnome-screenshot && has_gnome_shell; then
	args=()
	if (( opt_window )); then
		args+=(--window)
	elif (( opt_area )); then
		args+=(--area)
	fi
	if (( opt_delay )); then
		args+=(--delay=$opt_delay)
	fi
	gnome-screenshot "${args[@]}" --file="$file"
elif have scrot; then
	args=()
	if (( opt_window )); then
		args+=(-u -b)
	elif (( opt_area )); then
		args+=(-s -b)
	fi
	# TODO: implement opt_delay
	scrot "${args[@]}" "$file"
elif have maim && have slop; then
	args=()
	if (( opt_window )); then
		# XXX: 'xdotool getactivewindow' only reports the "real" window
		# and has no way to report the parent WM frame, so we must
		# select the window interactively.
		args+=(-s)
	elif (( opt_area )); then
		if (( opt_delay )); then
			geom=$(slop -f %g)
			sleep $opt_delay
			args+=(-g "$geom")
		else
			args+=(-s)
		fi
	fi
	maim "${args[@]}" "$file"
else
	vdie "no screenshot program"
fi

if [[ ! -s $file ]]; then
	notifysend -i error "Screenshot failed" &
	vdie "screenshot failed ('$file' not created)"
fi

shortfile=${file/#"$HOME/"/"~/"}

if (( opt_upload )); then
	url=$(cap-upload.sh "$file")
	if (( $? )); then
		notifysend -i error "Screenshot captured but upload failed" &
		echo "$file" | gclip
		echo "$file"
		vdie "screenshot upload failed"
	else
		notifysend -i "$file" "Screenshot captured and uploaded" "$url" &
		echo "$url" | gclip
		echo "$url"
	fi
else
	notifysend -i "$file" "Screenshot captured" "$shortfile" &
	echo "$file" | gclip
	echo "$file"
fi
