# Example: mozpath=/usr/bin/mozilla -width 1280 -height 1024
mozpath=/usr/bin/mozilla -width 1280 -height 1024
# Example: scrotpath=/usr/bin/scrot
scrotpath=/usr/bin/scrot
# Example: mogrifypath=/usr/bin/mogrify
mogrifypath=/usr/bin/mogrify
# Example: cropgeo=1269x884+3+120
cropgeo=1269x884+3+120
# Example: tempfile=/tmp/webshot.png
tempfile=/tmp/webshot.png

usage()
{
  echo "Usage: webshots.sh [-p prefix] [-d targetdir] controlfile.htm"
  echo ""
  echo "Will call a mozilla browser at $mozpath in full screen mode for each"
  echo "HTML link found in the control file and make a screen shot using scrot"
  echo "at $scrotpath."
  echo "The -c option calls mogrify at $mogrifypath to crop the screenshot"
  echo "to $cropgeo, to e.g. remove window widgets or browser GUI elements."
  echo "(Binary paths, crop geometry can be edited at the start of the script)."
  echo ""
  echo "The screen shots are renamed using prefix (if given) and the link text"
  echo "from the control file, then moved to targetdir (if given). targetdir"
  echo "must end in / (example: /foo/bar/)"
  echo ""
  echo "A note on browsers: This works best with mozilla (not firefox). Open"
  echo "one and zoom it manually to the desired window size, before starting this"
  echo "script. (The arguments -width and -height don't work with the current"
  echo "generation of mozilla browsers, therefore, you have to resize the browser"
  echo "manually.) The script will use the existing window for all screenshots---"
  echo "unlike firefox, that will open a new tab each time (which might get you"
  echo "out of memory soon). Make sure the browser window is on top after starting"
  echo "the script (you have 10 seconds do make it so). scrot makes a screenshot"
  echo "of the whole screen, including other windows."
  exit 0
}

file=
prefix=
directory=./
while [ $# -ge 1 ] 
do
  case $1 in
    -h) usage ;;
    -p) shift; prefix=$1 ;;
    -d) shift; directory=$1 ;;
    *) file=$1 ;;
  esac
  shift
done

if test tt$file = tt
then
  echo "Missing file argument."
  echo prefix:$prefix
  echo directory:$directory
  exit 0
fi

if test ! -f $file
then
  echo "File $file not found."
  exit 0
fi

echo "Checking for mozilla process..."
$mozpath -remote "ping()";
if test $? = 2
then
	$mozpath &
	sleep 5
fi

for i in $(grep -o 'href="[^<]*' $file|sed -e 's/ /_/')
do
	url=`echo $i|sed -e 's/href=.//'|sed -e 's/">.*//'`
	fn=`echo $i|sed -e 's/.*>//'|sed -e 's/[^a-zA-Z0-9]+/_/'`
	echo "Loading $url, storing under $directory$prefix$fn.png"
	$mozpath -remote "openurl($url)"
	sleep 10 
	scrot $tempfile
	$mogrifypath -crop $cropgeo +repage $tempfile
	mv $tempfile $directory$prefix$fn.png
done