#!/bin/bash
#
# Extract random images from fantom-xp.com
#
# -i            == info. IP, plus 0, 1, or 2 selections
# -m            == media type. Either "img" or "vid"
# -v            == Script version
# -l            == List all categories
# -c <category> == list themes of the Category ( sub-category )
# -t <theme>    == link to web page
# -r <targetFile> <category> <theme> == get random image off the page
#
######################################################################
#
# HDRCreme had 26095 images on pages with 30 images each -> 870 pages
#
#######################################################################

if [ "x$1" == "x-v" ]; then
  echo "1.0"
  exit
fi;

if [ "x$1" == "x-m" ]; then
  echo "img"
  exit
fi;

if [ "x$1" == "x-i" ]; then
cat << EOF
http://www.HDRCreme.com
EOF
fi;

if [ "x$1" == "x-r" ]; then
  target="$2"
  category="$3"
  theme="$4"
  link=
  imagesPerPage=30
  maxPages=870    # 26095 images / 30 img per page

  randPage=$(( $RANDOM%$maxPages ))
  link="http://hdrcreme.com/photo-gallery/page/"$randPage
  randImage=$(( $RANDOM%$imagesPerPage ))

  array=`wget --user-agent=MSIE -qO - "$link" | grep imgGalleri | sed -e 's,.*href=\",,g' -e 's,\".*,,g'`
  imageLink=`for link in $array; do
    if [ $randImage -eq 0 ]; then
      echo $link
      break 
    fi
    randImage=$(( randImage - 1 ))
  done`

  # /photos/22173-Old-Tram
  if [ ${imageLink:0:1} == "/" ]; then
    imageLink=http://hdrcreme.com$imageLink
  fi

  # imageLink is the link to the web page.
  PICURL=`wget --user-agent=MSIE -qO - "$imageLink" | grep \"showimagepic\" | sed -e 's,.*href=\",,g' -e 's,\".*,,g'`
  wget --user-agent=MSIE $PICURL -O "$target"
fi

