#!/bin/sh

# Params
#  1. full media file path
#  2. dir to save
#  3. number of image
#  4. scale to size
#  5. optional -force

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

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

if [ -d "$1" ]; then
  DIR="$1";
else
  DIR=`dirname "$1"`;
fi;

# do not search in $HOME or / (it can be wrong input)
if [ "x$DIR" = "x$HOME" ] || [ "x$DIR" = "x/" ]; then
  exit 1;
fi

IMAGE=`find "$DIR" -maxdepth 2 -type f -name "*[jpg|JPG|png|PNG]"|head -$3|tail -1`


if [ "x$IMAGE" = "x" ]; then
  
  # use default
  CONF_FIR=`dirname $0`
  
  DEF_COVER="$2"/default"-${4}.png"

  convert -resize $4x$4 -depth 8 -background transparent $CONF_FIR/../Icons/common/cover-audio.png $DEF_COVER 2> /dev/null;
  
  if [ -s $DEF_COVER ]; then
    echo "$2"/default"-${4}.png"
  else 
    exit 1;
  fi;
  
else

  IFILE=`echo "$IMAGE"|md5sum|cut -f 1 -d ' '`"-${4}.png"

  if [ "x$5" = "x-force" ]; then
     rm -f "$2"/"$IFILE"
  fi

  if [ ! -f "$2"/"$IFILE" ]; then
      convert -resize $4x$4 -depth 8 -background transparent "$IMAGE" "$2"/"$IFILE" 2> /dev/null;
  fi;

  if [ -s "$2"/"$IFILE" ]; then
    echo "$2"/"$IFILE"
  else 
    exit 1;
  fi;
  
fi

exit 0;
