#!/bin/sh

[ -r .conf ] || exit 125

NONA='nona -t 2 -o tmp-'
CCM='color_correct -E -l -p.03 -D64 -a-4096:4096+1024 -k24:40/32 -g28:36/32 -otmp.tiff'
ENBL='enblend -z -m 896 --fine-mask'
FGLB='fulla -t 2 -s -g 0.09:0.02:-0.9:1.75'
#CONV='convert -limit memory 512 -limit map 256'
CONV='convert'
INPNT='greycstoration -alpha 0.9 -sigma 0.2 -p 5 -a 1 -dt 20 -iter 5 -bits 16 -m mask.png -inpaint'
INPNT='greycstoration -verbose -init 4 -iter 2048 -bits 16 -inpaint'

LANG=C; export LANG

. .conf
DST="${DST}=360=90"

[ -n "${DEPTH}" ] || DEPTH="${2}"
[ -n "${DEPTH}" ] || DEPTH=16

rm -rf tmp
mkdir -p tmp
N=0
for n in ${SRC}
do
    o=$(printf '%02d' ${N})
    N=$((${N}+1))
    [ -r ${o}.tiff ] && continue
    [ -r ${n}.JPG ] || exit 126
    cp ${n}.JPG tmp/${o}.jpeg
done
sh ../../tools/orient tmp
for n in $(find tmp -type f)
do
    o=$(basename -s .jpeg ${n})
    ${CONV} ${n} \
        -depth ${DEPTH} -orient undefined \
        -enhance -unsharp 0x0.8 -resize 50% -unsharp 0x0.5 \
        -compress zip ${o}.tiff
    [ -r mask-${o}.png ] \
    && ${CONV} ${o}.tiff -matte \
        mask-${o}.png -compose multiply -composite \
        mask-${o}.png -channel A -fx 'v.r' \
        -compress zip ${o}.tiff
done
rm -rf tmp
[ "${1}" = prep ] && exit

#${NONA} ${DST}.pto \
#&& ${CONV} tmp-0050.tif -crop $((4096+16))x8192+$((4096-16))+0 tmp-0050a.tif \
#&& ${CONV} tmp-0050.tif -crop $((4096+16))x8192+0+0 tmp-0050.tif \
#&& rm [0-9][0-9].tiff \
#&& ${ENBL} -f 8192x8192 -o tmp.tiff tmp-0*.tif \
#&& rm tmp-0*.tif \
#&& ${CONV} tmp.tiff -crop 896x896+5752+5792 +repage -compress zip tmp.0.tiff \
#&& ${INPNT} tmp.0.tiff -m mask-${DST}.0.png -o tmp.0.tiff \
#&& ${CONV} tmp.tiff tmp.0.tiff -geometry 896x896+5752+5792 -compose src-over -composite -compress zip ${DST}.tiff \
#&& echo rm tmp*.tiff \
true \
&& ${CONV} ${DST}.tiff +matte -resize 7168x7168 -unsharp 0x0.5+0.6+0.04 -compress zip ${DST}.tiff \
&& ${FGLB} -o ${DST}.tiff ${DST}.tiff \
&& ${CONV} ${DST}.tiff -crop $((7168-768))x$((7168-768))+0+768 +repage -compress zip ${DST}.tiff \
&& ${CONV} ${DST}.tiff -resize x3072 -unsharp 0x0.75+0.8+0.04 -compress zip ${DST}.tiff \
&& ${CONV} ${DST}.tiff -gamma 1.55 -quality 90 ${DST}-huge.jpeg \
&& ${CONV} ${DST}.tiff -resize x1536 -unsharp 0x0.75+0.6+0.04 -compress zip ${DST}.tiff \
&& ${CONV} ${DST}.tiff -gamma 1.55 -quality 90 ${DST}-big.jpeg \
&& ${CONV} ${DST}.tiff -resize x768 -unsharp 0x0.75+0.6+0.04 -compress zip ${DST}.tiff \
&& ${CONV} ${DST}.tiff -gamma 1.55 -quality 90 ${DST}.jpeg \
&& ${CONV} ${DST}.tiff -resize x512 -unsharp 0x0.65+0.6+0.03 -compress zip ${DST}.tiff \
&& ${CONV} ${DST}.tiff -resize x256 -unsharp 0x0.65+0.6+0.03 -compress zip ${DST}.tiff \
&& ${CONV} ${DST}.tiff -gamma 1.6 -quality 90 ${DST}-small.jpeg \
&& rm ${DST}.tiff
exit
