#!/bin/sh

# Params
#  1. full media file path
#  2. scale to size
#  3. dir to save
#  4. cfg dir
#  5. optional: movie title

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

MOVIE_FILE=$1
SCALE=$2
SAVE_DIR=$3
CONF_FIR=$4

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

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

MOVIE_HASH=`echo "${MOVIE_FILE}"|md5sum|cut -f 1 -d ' '`
POSTER_HASH=${MOVIE_HASH}".jpg"
POSTER_SCALED_HASH=${MOVIE_HASH}"-${SCALE}.png"

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

  if [ "x$5" = "x" ]; then
    SEARCH_TITLE=`basename $MOVIE_FILE`
  else
    SEARCH_TITLE=$5
  fi;

  
  $CONF_FIR/Utils/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 \( $SAVE_DIR/posters/$POSTER_HASH -resize $SCALEx$SCALE \) -append $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 \( $CONF_FIR/Icons/common/video-default.svg -resize $SCALEx$SCALE \) -append $DEF_SCALED_POSTER 2> /dev/null;
  fi;
   
  if [ -f $DEF_SCALED_POSTER ]; then
    echo $DEF_SCALED_POSTER 
    exit 0;
  fi;

fi;

exit 1;
