#! /bin/bash
#
# zpng - use ZopfliPNG to optimize PNG files in place
# Copyright (c) 2025  Polyna <polyna@posteo.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
progname=${0##/*/}
tmpfile=

# Print warnings and errors.
function warn {
	printf '%s: %s\n' "$progname" "$*" >&2
}

function error {
	warn "$@"
	exit 1
}

# Check if ZopfliPNG is installed.
command -v zopflipng > /dev/null 2>&1 ||
	error 'ZopfliPNG is either not installed or not in the PATH'

# Check if at least one argument is provided.
if (( $# < 1 )); then
	warn 'missing file operand'
	printf 'Usage: %s FILE...\n' "$progname" >&2
	exit 1
fi

# Set up trap to clean up temporary file on exit or interruption.
trap '[[ -f $tmpfile ]] && rm -f -- "$tmpfile"' EXIT

# Process each PNG file.
for infile; do
	# Treat filenames starting with ‘-’ as literal filenames by prefixing
	# them with ‘./’.
	[[ $infile = -* ]] &&
		infile=./$infile

	# Check if an input file exists.
	if [[ ! -f $infile ]]; then
		warn "$infile: No such file"
		continue
	fi

	# Optimize the file.
	tmpfile=$(mktemp) ||
		error 'A temporary file could not be created'

	if zopflipng -my "$infile" "$tmpfile"; then
		mv -- "$tmpfile" "$infile"
	else
		warn "$infile: Optimization failed"
		rm -f -- "$tmpfile"
	fi
	tmpfile=
done
