#!/bin/bash
#
# convert-png-jpg.sh v1.0 2006/07
#
# shell script for recursively converting .png images to .jpg format to
# save space and bandwidth (for web serving).
#
# Copyright (C) 2006 by Pedro Venda < pjvenda (at) pjvenda org >
#
# Distributed under the terms of the GNU Public License Agreement (GPLv2)
# http://www.fsf.org/licensing/licenses/gpl.html or
# http://www.fsf.org/licensing/licenses/gpl.txt
#
# Usage
# =====
#
# - run script with one argument: the base directory.
# example: ./convert-png-jpg.sh /var/www/localhost/htdocs
# - look at output to see which images were converted and how
# much space can be spared
#
# Changelog
# =========
#
# v1.0 - 2006/07/01
# - initial version

QUALITY=95

PNG_TOTAL_SIZE=0
JPG_TOTAL_SIZE=0

CONVERT=/usr/bin/convert
RM=/usr/bin/rm
DU=/usr/bin/du
FIND=/usr/bin/find
AWK=/usr/bin/awk
BASENAME=/usr/bin/basename
DIRNAME=/usr/bin/dirname

if [ "${1}" == "" ]; then
  echo "usage: ${0} base_directory"
  echo ""
  echo "this script will recursively convert images from .png to .jpg to save"
  echo "space and bandwidth."
  echo ""
  echo "NOTES/WARNINGS:"
  echo "  - Unlike .png, the .jpg format cannot handle transparencies, so be"
  echo "  careful with your transparent .png images - the conversion WILL go"
  echo "  wrong."
  echo "  - This script will not remove converted .png files. that's up to you"
  echo "  or another script (clear-png.sh for example)."
  echo "  - Please look at the results before considering them ok."
  echo ""
  exit 1
fi

for FILE in $(${FIND} ${1} -name '*.png'); do 

	PNG_FILE="${FILE}"
	PNG_FILE_SIZE=$(${DU} -sk "${PNG_FILE}" | ${AWK} ' { print $1 } ')
	PNG_TOTAL_SIZE=$((${PNG_TOTAL_SIZE}+${PNG_FILE_SIZE}))
	JPG_FILE="$(${DIRNAME} ${PNG_FILE})/$(${BASENAME} ${PNG_FILE} .png).jpg"

	echo -n "${PNG_FILE} -> "

	${CONVERT} -quality ${QUALITY} ${PNG_FILE} ${JPG_FILE}

	if [ -f ${JPG_FILE} ]; then
		JPG_FILE_SIZE=$(${DU} -sk ${JPG_FILE} | ${AWK} ' { print $1 } ')
		if [ ${JPG_FILE_SIZE} -lt ${PNG_FILE_SIZE} ]; then
			JPG_TOTAL_SIZE=$((${JPG_TOTAL_SIZE}+${JPG_FILE_SIZE}))
			DIFF_FILE_SIZE=$((${JPG_FILE_SIZE}-${PNG_FILE_SIZE}))
			echo "${JPG_FILE} (${DIFF_FILE_SIZE} K)"
		else
			echo "jpg would be bigger"
			${RM} -f ${JPG_FILE}
		fi
	else
		echo "unable to create jpg file"
	fi
done

echo ""
echo "sum of png files: ${PNG_TOTAL_SIZE}K"
echo "sum of jpg files: ${JPG_TOTAL_SIZE}K"
