#!/bin/bash
#
# clear-converted-png.sh v1.0 - 2006/07
#
# this script will read the output of the convert-png-jpg.sh and remove all
# converted .png images
#
# 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
# =====
#
# this script needs one argument: the output file of a convert-png-jpg.sh run.
# example: ./clear-converted-png.sh output-1.log
# example: cat output-1.log | ./clear-converted-png.sh -
#
# Changelog
# =========
#
# v1.0 - 2006/07/01
# - initial version
#

CAT=/usr/bin/cat
EGREP=/bin/egrep
BASENAME=/usr/bin/basename
DIRNAME=/usr/bin/dirname
AWK=/usr/bin/awk
RM=/usr/bin/rm
DU=/usr/bin/du

LINE_IGNORE="(sum.*|^[ \t]*$)"

usage_help() {
	echo "usage: ${0} {input_file|-}"
	echo ""
	echo "This script will read the output of convert-jpg-png.sh and remove"
	echo "the converted .png images."
	echo ""
	echo "NOTES/WARNINGS:"
	echo "  - THIS SCRIPT WILL ERASE SOME .png FILES."
	echo "  - It can be very hard to recover erased files, be sure"
	echo "  that you know what't you're doing."
	echo "  - Only .png files that were effectively converted to .jpg"
	echo "  (according to the input file) are removed."
	echo "  - All .png file that were effectively converted to .jpg"
	echo "  (according to the input file) are removed."
}

if [ "${1}" == "" ]; then
	usage_help
	exit 1
elif [ "${1}" == "-" ]; then
	INPUT_FILE=/dev/stdin
elif [ ! -f ${1} ]; then
	echo "unable to open input file ${1}"
	echo ""
	usage_help
	exit 1
else
	INPUT_FILE=${1}
fi

PNG_TOTAL_SIZE=0

while read LINE; do
	PNG_FILE=$(echo ${LINE} | ${AWK} ' { print $1 } ')
	JPG_FILE=$(echo ${LINE} | ${AWK} ' { print $3 } ')

	if [ ! "${PNG_FILE}" == "$(${DIRNAME} ${JPG_FILE})/$(${BASENAME} ${JPG_FILE} .jpg).png" ]; then
		continue
	fi

	if [ ! -f ${PNG_FILE} ]; then
		continue
	fi

	PNG_FILE_SIZE=$(${DU} -sk ${PNG_FILE} | ${AWK} ' { print $1 } ')

	echo "${PNG_FILE} (${PNG_FILE_SIZE} K)"
	${RM} -f ${PNG_FILE}
	PNG_TOTAL_SIZE=$((${PNG_TOTAL_SIZE}+${PNG_FILE_SIZE}))
	
done < <(${CAT} ${INPUT_FILE} | ${EGREP} -v "${LINE_IGNORE}")

echo ""
echo "total space freed: ${PNG_TOTAL_SIZE}K"
