#!/usr/bin/env bash
# Screenshot Program for X11
# @author	jebug29
# @date-mod	2019 Mar 24
# @version	0.1

docopy=0
ext=".png"
if [ "$1" = "copy" ] || [ "$2" = "copy" ]; then 
	docopy=1
	ext=".jpg"
fi

use_copyq=0

if [ "$( pgrep copyq | wc -l )" -gt 0 ]; then
	use_copyq=1
	ext=".png"
fi

filename="/tmp/scrshot$(uuid)$ext"
if [ -z "$screensdir" ]; then
	screensdir="$HOME/screenshots"
fi

mkdir -p "$screensdir"

case "$1" in
	window)
	scrot -u "$filename"
	;;
	*)
	scrot "$filename"
	;;
esac

if [ ! -f "$filename" ]; then
	echo "Error writing to file $filename" >&2
	exit 1
fi

mimetype=$( file -b --mime-type "$filename" )

debug=0
if [ "$debug" -eq 1 ]; then
printf \
"Copy?:\t\t$docopy
Ext.:\t\t$ext
Filename:\t$filename
Savedir:\t$screensdir
Mimetype:\t$mimetype
copyq:\t\t$use_copyq
"
fi

if [ "$docopy" -eq 1 ]; then
	if [ "$use_copyq" -eq 1 ]; then
		copyq write "$mimetype" - < "$filename" && copyq select 0
	else
		xclip -selection clipboard -t "$mimetype" -i "$filename"
	fi
	rm "$filename"
else
	newfn="$(date "+%Y-%m-%d %H:%M:%S")"
	count=""
	while [ -f "$screensdir/$newfn $count$ext" ]; do
		if [ -z "$count" ]; then count=0; fi
		count=$(( count++ ))
	done
	newfn="$screensdir/$newfn"
	if [ ! -z "$count" ]; then newfn="$newfn $count"; fi
	newfn="$newfn.png"

	mv "$filename" "$newfn"
fi
