#!/usr/local/bin/bash
#To run: /vws/iwbs/scripts/adaptimage_creator

#DIR=("/vws/iwbs/anteh.ru/anteh.ru" "/vws/iwbs/anteh.com/anteh.com")
DIR=("/path/to/site1" "/path/to/site2" "/path/to/site3")
DocumentRoot="/doc/root"
Resolution=(320 480 600 800 1024 1280)
HandleIfExists=true; #Not debugged

smartresize() {
mogrify -path $3 -filter Triangle -define filter:support=2 -thumbnail $2 \
-unsharp 0.25x0.08+8.3+0.045 -dither None -posterize 136 -quality 60 \
-define jpeg:fancy-upsampling=off -define png:compression-filter=5 \
-define png:compression-level=9 -define png:compression-strategy=1 \
-define png:exclude-chunk=all -interlace none -colorspace sRGB $1
}

echo "HOSTS: ${DIR[*]}"
for s in ${DIR[@]}
do	
    echo -e "\nHandle hosts dir: ${s}\n"
    #CREATE NOT PATH DIRS
    NotPath=""
    for np in ${Resolution[@]}; do NotPath+=" -not -path */$np*"; done
    echo -e $NotPath

    #DIRF array with all files to handle
    DIRF=()
    DIRD=$( find ${s} -type d $NotPath )
    for dirr in ${DIRD[@]}; do 
	DIRFB=$( find $dirr -maxdepth 1 -type f -name "*.png" -or -name "*.gif" -or -name "*.jpg" )
	DIRF=("${DIRF[@]}" "${DIRFB[@]}")
    done

    #Create folder
	for p in ${DIRF[@]}
	do
	    filename="${p##*/}" #file name
	    dirname="${p%/*}" #dir name

	    ds=$(echo $dirname | sed 's@'$s'@@')

	    for r in ${Resolution[@]} 
	    do
		dstr=$s'/'$r$ds
		if [ ! -d "$dstr" ]; then mkdir -p "$dstr"; fi
		sourcefile=$p
		realfile=$dstr'/'$filename
		#Handle file if does not exists or HandleIfExists=true
		if ([ -f "$realfile" ] && [ $HandleIfExists ]) || [ ! -f "$realfile" ];	then
		    width=$(identify -format '%w' $sourcefile)
		    if [ $width -gt $r ]; then
			smartresize $p $r $dstr
		    else #test check
			smartresize $p $width $dstr
		    fi
		    BeforeSize=$(wc -c <"$p")
                    AfterSize=$(wc -c <"$realfile")
                    if [ $AfterSize -gt $BeforeSize ]; then cp -f $p $realfile; fi
		    BeforeSize=$(wc -c <"$p")
		    AfterSize=$(wc -c <"$realfile")
		    echo -e "Before/After $BeforeSize/$AfterSize"
                    echo -e "$p\n$realfile"

		    #ADD WATERMARKS TO $realfile
		    convert -size 160x90 xc:none -pointsize 16 -fill "rgba(192,192,192,0.50)" -gravity NorthWest -draw "rotate 15 text 10,10 'anteh.ru'" -gravity SouthEast -draw "rotate 15 text 5,15 'anteh.ru'" miff:- | composite -tile - $realfile $realfile
		fi
	    done
	done
done
exit 0
