#!/bin/bash

#   FILE: screenqt -- 
# AUTHOR: W. Michael Petullo <mike@flyn.org>
#   DATE: 20 January 2002
#
# Copyright (C) 2002 W. Michael Petullo <mike@flyn.org>
# All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

RESOLUTION="640x480"
FRAMERATE="30"

USAGE="-o <output> -c <frames> [OPTION]...

  -h, -?   print this message
  -f rate  set output video's frame rate  [ $FRAMERATE ]
  -n name  capture only from the window with the specified WM_NAME property
  -r res   set output video's resolution  [ $RESOLUTION ]"

while :;
	do case "$1" in
		-h | "-?" )	
			echo -e usage: ${0##*/} "$USAGE" >&2
			exit 1 ;;
		-o )
			OUT=$2
			shift ;;
		-c)
			FRAMES=$2
			shift ;;
		-f)
			FRAMERATE=$2
			shift ;;
		-n)
			NAME=$2
			shift ;;
		-r)
			RESOLUTION=$2
			shift ;;
		-?* )
			echo "${0##*/}: unrecognised option: $1" >&2
			exit 1 ;;
		* )
			break ;;
	esac
	shift
done

if [ -z $OUT ]; then
        echo "${0##*/}: output not specified" >&2
	exit 1
fi

if [ -z $FRAMES ]; then
        echo "${0##*/}: frame count not specified" >&2
	exit 1
fi
	
XWD=`mktemp -d /tmp/screenqt.XXXXXX`
PPM=`mktemp -d /tmp/screenqt.XXXXXX`
JPG=`mktemp -d /tmp/screenqt.XXXXXX`
trap 'rm -rf $XWD $PPM $JPG' SIGHUP SIGINT SIGTERM EXIT

I=0
while true; do
	if [ x$I = x$FRAMES ]; then break; fi
	if [ -z $NAME ]; then
		xwd -root -silent > $XWD/$I.xwd
	else
		xwd -name "$NAME" -silent > $XWD/$I.xwd
	fi
	I=$(($I + 1))
	sleep `echo foo | awk "{ print 1 / $FRAMERATE }"`
done

I=$(($I - 1))

while true; do
	if [ x$I = x0 ]; then break; fi
	xwdtopnm $XWD/$I.xwd > $PPM/$I.ppm
	ppmtojpeg $PPM/$I.ppm > $JPG/$I.jpg
	mogrify -geometry $RESOLUTION $JPG/$I.jpg
	I=$(($I - 1))
done

qtsg -r $FRAMERATE -o $OUT $JPG/*
