#! /bin/bash

LOG_FILE="$ALBERT/log/pp_extension.log"
ERRORS_DIR="errors"
FILENAME="$1/$2_$3"

function log {
	echo `date +"%y-%m-%d %H:%M:%S"`"	$1" >> $LOG_FILE
}

function logoError {
	mv "$1" `echo $1 | sed "s/\(\/[^\/]\+\)$/\/$ERRORS_DIR\1/"`
	exit 1
}

if [ ! -f $FILENAME ]; then
	log "Error: File '$FILENAME' not found."
	exit 1
fi

# Extract file format
FORMAT=`file $FILENAME | sed 's/^[^:]\+: \([^,]\+\)\(,.*\|$\)/\1/'`

EXT=""

case "$FORMAT" in
	"JPEG image data") EXT="jpg" ;;
	"PNG image data") EXT="png" ;;
	"GIF image data") EXT="gif" ;;
	"PC bitmap") EXT="bmp" ;;
esac

if [ "$EXT" == "" ]; then
	log "Warning: Unsupported format: '$FORMAT' extracted from '`file $FILENAME`'"
	logoError "$FILENAME"
else
	# log "Info: Successfully detected format '$FORMAT' for file '$1'."
	convert "$FILENAME" -resize 150x150\> -quality 90\> -strip "$FILENAME"
	RET=$?
	if [ $RET != 0 ]; then
		log "Error: convert tool returned an error $RET on file '$FILENAME'."
		logoError "$FILENAME"
	fi
	mv "$FILENAME" "$FILENAME.$EXT"
	echo "$2_$3.$EXT" > "$1/$2.info"
fi

