#!/bin/sh

# Params
#  1. -poster|-force_poster|-hash
#  2. full media file path
#  3. scale to size
#  4. dir to save
#  5. cfg dir
#  6. optional: movie title

if [ "x$1" = "x" ] || [ "x$2" = "x" ]; then
   exit 1;
fi

OPERATION=$1
MOVIE_FILE="$2"

MOVIE_HASH=`echo "$MOVIE_FILE"|md5sum|cut -f 1 -d ' '`

if [ "x$OPERATION" = "x-hash" ]; then
  echo $MOVIE_HASH
  exit 0;
fi


if [ "x$3" = "x" ] || [ "x$4" = "x" ] || [ "x$5" = "x" ]; then
   exit 1;
fi

SCALE=$3
SAVE_DIR="$4"
CONF_DIR="$5"

if [ ! -d "$SAVE_DIR" ]; then
    mkdir "$SAVE_DIR";
fi;

if [ ! -d "$SAVE_DIR/posters" ]; then
    mkdir "$SAVE_DIR/posters";
fi;

if [ ! -f $HOME/.anyRemote/imdb-mf.sh ]; then
    curl -k -g https://raw.github.com/webofunni/imdb-movie-fetcher/master/imdbmoviefetcher/imdb-mf.sh > $HOME/.anyRemote/imdb-mf.sh
    chmod u+x $HOME/.anyRemote/imdb-mf.sh
fi;

if [ ! -f $HOME/.anyRemote/imdb-mf.sh ]; then
   exit 1;
fi

POSTER_HASH=${MOVIE_HASH}".jpg"
POSTER_SCALED_HASH=${MOVIE_HASH}"-${SCALE}.png"

if [ "x$OPERATION" = "x-force_poster" ]; then
  rm -f $SAVE_DIR/$MOVIE_HASH
  rm -f $SAVE_DIR/posters/$POSTER_HASH
  rm -f $SAVE_DIR/posters/$POSTER_SCALED_HASH
fi

if [ ! -f $SAVE_DIR/$MOVIE_HASH ]; then

  if [ "x$6" = "x" ]; then
    SEARCH_TITLE=`basename "$MOVIE_FILE"|sed "s/.avi//g;s/.mkv//g;s/.mp4//g"`
  else
    SEARCH_TITLE="$6"
  fi;

  $HOME/.anyRemote/imdb-mf.sh -m -t "$SEARCH_TITLE" > $SAVE_DIR/${MOVIE_HASH}.tmp

  GOT=`grep "imdb.com" $SAVE_DIR/${MOVIE_HASH}.tmp|grep "Poster URL" | wc -l`
  
  if [ $GOT -eq 0 ]; then
     rm -f $SAVE_DIR/${MOVIE_HASH}.tmp;
  else
     mv $SAVE_DIR/${MOVIE_HASH}.tmp $SAVE_DIR/$MOVIE_HASH;
  fi;
  
fi;

if [ -f $SAVE_DIR/$MOVIE_HASH ] && [ ! -s $SAVE_DIR/posters/$POSTER_HASH ]; then

  POSTER=`grep "Poster URL :" $SAVE_DIR/$MOVIE_HASH| sed "s/Poster URL : //"`

  curl -s $POSTER > $SAVE_DIR/posters/$POSTER_HASH  
  
fi;

if [ -f $SAVE_DIR/posters/$POSTER_HASH ] && [ ! -s $SAVE_DIR/posters/$POSTER_SCALED_HASH ]; then
  
  convert -resize $SCALEx$SCALE -depth 8 -background transparent $SAVE_DIR/posters/$POSTER_HASH $SAVE_DIR/posters/$POSTER_SCALED_HASH 2> /dev/null;
  
fi;

#if [ -f $SAVE_DIR/posters/$POSTER_SCALED_HASH ]; then
#  echo $SAVE_DIR/posters/$POSTER_SCALED_HASH 
#  exit 0;
#else
#  # use default poster
#  
#  DEF_SCALED_POSTER=$SAVE_DIR/posters/default"-${SCALE}.png"
#  
#  if [ ! -s $DEF_SCALED_POSTER ]; then
#    convert -resize $SCALEx$SCALE -depth 8 -background transparent $CONF_DIR/Icons/common/cover-video.png $DEF_SCALED_POSTER 2> /dev/null;
#  fi;
#   
#  if [ -f $DEF_SCALED_POSTER ]; then
#    echo $DEF_SCALED_POSTER 
#    exit 0;
#  fi;
#
#fi;

exit 1;
