#!/bin/sh
# imgresize
# Written in 2019-2020 by Lucas
# CC0 1.0 Universal/Public domain - No rights reserved
#
# To the extent possible under law, the author(s) have dedicated all
# copyright and related and neighboring rights to this software to the
# public domain worldwide. This software is distributed without any
# warranty. You should have received a copy of the CC0 Public Domain
# Dedication along with this software. If not, see
# <http://creativecommons.org/publicdomain/zero/1.0/>.

usage()
{
	cat - <<. >&2
Usage:
	${0##*/} size in-file out-file

"size" is WxH or Wx or xH.
.
	exit 1
}

err()
{
	printf "%s: %s\n" "${0##*/}" "$*" >&2
	exit 1
}

check_dimension_format()
{
	printf "%s\n" "$1" | grep -q "^[0-9]*x[0-9]*\$" && [ "$1" != "x" ]
}

[ $# -eq 3 ] && check_dimension_format "$1" || usage
[ -n "$2" ] || err "input file name can't be empty"
[ -n "$3" ] || err "output file name can't be empty"

size=$1
w=${size%x*}
h=${size#*x}
infile=$2
outfile=$3

inprog=
case $infile in
*.jpg | *.jpeg)
	inprog=jpegtopnm
	;;
*.png)	inprog=pngtopam
	;;
*)	err "unknown input format"
	;;
esac

outprog=
case $outfile in
*.jpg | *.jpeg)
	outprog=pnmtojpeg
	;;
*.png)	outprog=pamtopng
	;;
*)	err "unknown output format"
	;;
esac

$inprog <"$infile" |
    pamscale ${w:+-width "$w"} ${h:+-height "$h"} |
    $outprog >"$outfile"
