#!/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
#
##################################################

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

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

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

if [ "x$1" == "x-r" ]; then
  target="$2"
  category="$3"
  theme="$4"

  link=
  maxFile=271
  rand=$(( $RANDOM%$maxFile ))
  screenshot=`basename $target vob`jpg
  screenshot=`dirname $target`/$screenshot

  wget --user-agent=MSIE --post-data="Cmd=Download&AL=Yes&&ID=$rand" http://www.dreamscene.org/load.php -O /tmp/Dream.zip
  file=`unzip -Z /tmp/Dream.zip | grep "b- defN" | awk '{ for ( i=9;i<=NF;i++) printf $i }'`
  cd /tmp
  if [ -e Dream.zip ]; then
    unzip -o Dream.zip
  fi;
  if [ -e "$file" ]; then
    ffmpeg -i "$file" -ar 48000 -ab 224k -ac 2 -acodec ac3 -y -s 720x480 -b 9900k -f vob "$target"
    ffmpeg -an -y -t 00:00:01  -vframes 1 -i "$target" -y -f image2 "$screenshot"
  fi;
fi

