#!/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 \( $CONF_FIR/../Icons/common/audio-default.svg -resize $4x$4 \) -append $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 \( "$IMAGE" -resize $4x$4 \) -append "$2"/"$IFILE" 2> /dev/null;
  fi;

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

exit 0;
