#!/bin/bash

#make sure firefox launches in the bottom right corner of the window

# read URLs from a data file in a loop
#regex='([^[:space:]]+)[[:space:]]*(.*)'
regex='([^[:space:]]+)[|]([^|]+)[|](.*)'

func() {
    if [ -n "$2" ]
    then
      url=$1
      name=$2
    else
      [[ $1 =~ $regex ]]
      url=${BASH_REMATCH[1]}
      name=${BASH_REMATCH[2]}
      desc=${BASH_REMATCH[3]}
    fi

    #                  remove middle space,  lowercase
    name=`echo $name | tr -d '[[:space:]]' | tr '[A-Z]' '[a-z]'`

    if [ -n "$name" ]
    then
      close_firefox

      # send URL to the firefox session
      # firefox --width 1030 --height 768 $url &
      /Applications/Firefox.app/Contents/MacOS/firefox --width 1030 --height 768 $url &
      echo started firefox with $url
      echo preparing screencapture ...

      # take a picture after waiting a bit for the load to finish
      sleep 6
      # gm import -window root -crop 1004x768+414+228 -resize 500x350 $name.png
      screencapture -wo $name.png
      gm convert $name.png -crop 1004x768+0+80 -resize 200x140 $name.png
      echo grabbed screenshot $name.png
    else
      echo missing name $1 $2
    fi
}

close_firefox() {
  if ps ax | grep -v grep | grep firefox > /dev/null
  then
    echo waiting for manual firefox shutdown...
  fi

  while true; do
    if ps ax | grep -v grep | grep firefox > /dev/null
    then
      sleep 1
    else
      break
    fi
  done
  echo firefox shutdown detected
}

if test -z "$1"
then
  while read line
  do
      func $line
  done < urls
else
  func $1 "$2"
fi

