#!/bin/bash
sortF="sort.tmp"
shootMaxSize="1920"

function getDate ()
{
    for row in "Create Date" "File Modification Date\/Time"; do
        shootDate=`exiftool $1 | grep "$row" | sed -e "s/$row\\ *: //g" | head -n 1`
        if [ "$shootDate" != "" ] ; then
            return 0
        fi
    done
    echo "File "$1" has no shooting date in exif. Exiting."
    exit
}

function getResolution ()
{
    shootHeight=$(exiftool $1 | grep -E "^Image Height" | sed -e "s/Image Height\\ *: //g" | head -n 1)
    shootWidth=$(exiftool $1 | grep -E "^Image Width" | sed -e "s/Image Width\\ *: //g" | head -n 1)
    if [ "$shootWidth" -ge "$shootHeight" ]
    then
        shootSize=$shootWidth
    else
        shootSize=$shootHeight
    fi
}

# rename lowercase
rename 'y/A-Z/a-z/' *

# read shooting date
rm -f $sortF
for file in *; do
    getDate $file
    echo $shootDate" "$file >> $sortF
    echo -n "."
done
echo ""

sort $sortF > $sortF".tmp" && mv $sortF".tmp"  $sortF

# sort by shhoting date
index="0"
while read line
do
    read -a array <<< "$line"
    oldname=${array[2]}
    IFS='.' read -a array <<< "$oldname"
    oldname=${array[0]}
    oldsuff=${array[1]}
    file=$oldname"."$oldsuff

# set permissions
    setfacl -m g:webmaster-fykos:rw  $file
    setfacl -m u:www-data:r  $file
# reshootMaxSize if too large
    getResolution $file
    if [ "$shootSize" -gt "$shootMaxSize" ]
    then
        echo -n "Downscaling: "$file" "
        convert $file -resize ${shootMaxSize}x${shootMaxSize} $file
    fi
    mv $file foto_$(printf %04d $index)"."$oldsuff".new"
    index=$(($index+1))
done < $sortF

for file in *.new; do
    IFS='.' read -a array <<< "$file"
    touch $file
    mv $file ${array[0]}.${array[1]}
done

rm -f $sortF

# remove cache
echo "Sort snad OK."
echo "Run: wget \""$(pwd | sed -e "s/.*media\/\(.*\)foto/fykos.cz\/\1galerie/g")"?purge=true\" -O /dev/null"

