#!/bin/bash
#
# Strip image headers (profiles, comments)
# Author: John Angel, johnange at gmail.com, Dec 2008
# Contributor: Fabien Udriot, fabien.udriot@ecodev.ch, Dec 2008

# Adapt the PATH according to your environment
PATH_JPEGTRAN="/usr/local/php5/bin/"
PATH_CONVERT="/usr/local/imagemagick/bin/"

test=0

if [ $# -lt 1 ]
then
        echo "Strips image headers"
        echo "Usage: strip_image_headers.sh [test] directory"
        exit
fi

# Check if the first parameter is 'test'
if [ "$1" = "test" ]
then
        test=1
        directory=$2
else
        directory=$1
fi

if [ ! -d $directory ]
then
        echo "Directory $directory does not exist!"
        exit
fi

for i in $(find $directory/* -iname "*.jpg" -o -iname "*.jpeg" -o -iname "*.png" -o -iname "*.gif")
do

# Get image extension
ext="${i/*./}"

# Choose utility for stripping
case $ext in
jpg) transform=$PATH_JPEGTRAN"jpegtran -optimize -copy none -outfile tempimage.$ext $i";;
jpeg) transform=$PATH_JPEGTRAN"jpegtran -optimize -copy none -outfile tempimage.$ext $i";;
*) transform=$PATH_CONVERT"convert -strip $i tempimage.$ext";;
esac

echo -n "$i  "
if [ `/bin/expr "$i" : ".* "` -gt 0 ]
then
        echo "Space detected in filename - skipping."
        continue
fi

$transform

if test $? -ne 0; then
        echo "Error transforming - skipping."
else
        size1=$(ls -al "$i" | awk '{ print $5 }')    
        size2=$(ls -al "tempimage.$ext" | awk '{ print $5 }')

        echo -n "src: $size1  dst: $size2   "

        if [[ "$size1" -le "$size2" ]]
        then
                echo "New size is not smaller - skipping."
        else
                if test $test -eq 0; then
                        echo "Replacing old image."
                        mv "tempimage.$ext" "$i"
                else
                        echo "No replacing - just testing."
                fi
        fi
fi
done
