#!/usr/bin/bash
#
# @package      hubzero-mw-session
# @file         screenshot
# @author       Rick Kennell <kennell@purdue.edu>
# @author       Nicholas J. Kisseberth <nkissebe@purdue.edu>
# @copyright    Copyright (c) 2008-2015 HUBzero Foundation, LLC.
# @license      http://opensource.org/licenses/MIT MIT
#
# Copyright (c) 2008-2015 HUBzero Foundation, LLC.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# HUBzero is a registered trademark of HUBzero Foundation, LLC.
#

# @TODO: A custom X11 screenshot utility would be beneficial, capturing the
#        root window directly and writing PNG natively, with no external tool

PATH=/usr/bin:/bin
export PATH

# report failure from any stage of the capture pipeline, not just the last
# one. requires bash, hence the shebang above.
set -o pipefail

tmpfile=

cleanup()
{
	if [ "$tmpfile" != "" ]
	then
		rm -f "$tmpfile"
	fi
}

trap cleanup EXIT INT TERM

# pick a capture method. the xwd pipeline is preferred: it is lighter and is
# what every distribution shipped until EL10 dropped xorg-x11-apps. where xwd
# is unavailable, fall back to ImageMagick's import. checking up front turns a
# bare "command not found" into something actionable.
if command -v xwd > /dev/null 2>&1 &&
   command -v xwdtopnm > /dev/null 2>&1 &&
   command -v pnmtopng > /dev/null 2>&1
then
	capture_method=xwd
elif command -v import > /dev/null 2>&1
then
	capture_method=import
else
	echo "$0: no screen capture tool found, install either" 1>&2
	echo "  x11-apps and netpbm (Debian), xorg-x11-apps and netpbm-progs (RHEL), or" 1>&2
	echo "  imagemagick (Debian), ImageMagick (RHEL)" 1>&2
	exit 4
fi

# capture the root window to $1, in PNG format.
#
# import is given an explicit png: prefix rather than relying on the file
# extension: the save-to-file path below passes an mktemp name with no
# extension for ImageMagick to infer a format from.
capture()
{
	if [ "$capture_method" = "xwd" ]
	then
		xwd -silent -root | xwdtopnm | pnmtopng > "$1"
	else
		import -silent -window root png:"$1"
	fi
}

if [ "$DISPLAY" = "" ]
then
	echo "$0: No DISPLAY variable set" 1>&2
	exit 4
fi

if [ "$1" = "" ]
then
	time=$(date +%Y-%m-%d-%H%M%S)

	if ! command -v exportfile > /dev/null 2>&1
	then
		echo "$0: exportfile not found, install hubzero-filexfer" 1>&2
		exit 4
	fi

	tmpfile=/tmp/screenshot-${time}.png

	if capture "$tmpfile" && [ -s "$tmpfile" ]
	then
		# exportfile -d owns the file from here on, so keep the
		# exit trap from deleting it out from under the transfer
		shot="$tmpfile"
		tmpfile=
		exportfile -d "$shot"
	else
		echo "$0: screen capture failed" 1>&2
		exit 5
	fi
else

	dirname=`dirname "$1"`
	basename=`basename "$1"`
	if [ "$dirname" = "" ]
	then
		exit 1
	fi
	if [ "$basename" = "" ]
	then
		exit 2
	fi

	if [ -f "$1" ]
	then
		if [ $(( $(date +%s) - $(stat -L --format %Y "$1") )) -lt 60 ]
		then
			echo "$1 is newer than 60 seconds"
			exit 0
		fi
	fi

	tmpfile=`mktemp --tmpdir="$dirname" "$basename-XXXXXXXXXX"`
	if [ "$tmpfile" = "" ]
	then
		exit 3
	fi
	# we don't redirect directly to the target file because
	# it leaves us with 1-5 seconds of missing screenshot
	# data as bash truncates the file before even starting
	# the pipeline. cp keeps inode same (might be beneficial
	# but not relied upon as far as I know)
	#
	# an empty tmpfile means the capture failed: a missing converter, or
	# an X error such as BadDrawable when the framebuffer is resized out
	# from under the capture. copying it would replace a good screenshot
	# with a 0 byte file, so leave the target alone and report it.
	if capture "$tmpfile" && [ -s "$tmpfile" ]
	then
		cp "$tmpfile" "$1"
	else
		echo "$0: screen capture failed, $1 left unchanged" 1>&2
		exit 5
	fi
fi
