#!/usr/bin/env bash

command -v convert >/dev/null 2>&1 || { echo >&2 "I require convert (imagemagick) but it's not installed. Aborting."; exit 1; }
command -v optipng >/dev/null 2>&1 || { echo >&2 "I require optipng but it's not installed. Aborting."; exit 1; }

CURRENT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"

IMAGES_CACHE_FOLDER="${CURRENT_DIR}/cache"
IMAGES_RAW_FOLDER="${IMAGES_CACHE_FOLDER}/01_raw_images"
IMAGES_OPTIMIZED_FOLDER="${IMAGES_CACHE_FOLDER}/02_optimized_images"

RESIZE_OPTION="640x640"
CROP_PARAMETERS="-auto-orient +repage -gravity center -background white -extent ${RESIZE_OPTION}^"
CONVERT_OPTIONS="-alpha off -dither FloydSteinberg -colors 256 -depth 4"

OPTIPNG_OPTIONS="-preserve -quiet -o7"

echo "Cleaning empty/temp files..."
find "${IMAGES_CACHE_FOLDER}" -type f -name "*.png" -empty -exec rm {} \;
find "${IMAGES_CACHE_FOLDER}" -type f -name "*.tmp*" -exec rm {} \;

echo "Cleaning existing optimized images..."
find "${IMAGES_OPTIMIZED_FOLDER}" -type f -name "*.png" -exec rm {} \;

IMAGES="$(find "${IMAGES_RAW_FOLDER}" -type f -name "*.??g" | sort)"

while read -r INPUT_FILE; do
  if [[ -n "${INPUT_FILE}" ]]; then
    CATEGORY="$(basename "$(dirname "${INPUT_FILE}")")"
    echo "CATEGORY: ${CATEGORY}"
    HASH="$(echo "${INPUT_FILE%.*}" | md5sum | cut -c1-32)"
    OUTPUT_FILE="${IMAGES_OPTIMIZED_FOLDER}/${CATEGORY}_${HASH}.png"
    echo "  OUTPUT_FILE: ${OUTPUT_FILE}"

    if [[ -f "${OUTPUT_FILE}" ]]; then
      echo "   - Already optimized"
    else
      mkdir -p "$(dirname ${OUTPUT_FILE})"

      echo "   + Converting..."
      convert "${INPUT_FILE}" -resize "${RESIZE_OPTION}^" ${CROP_PARAMETERS} ${CONVERT_OPTIONS} "${OUTPUT_FILE}"
      echo "   + Optimizing..."
      optipng ${OPTIPNG_OPTIONS} "${OUTPUT_FILE}"
    fi
  fi
done < <(echo "${IMAGES}")

echo "done."
