#! /bin/bash

# Check dependencies
command -v inkscape >/dev/null 2>&1 || { echo >&2 "I require inkscape but it's not installed. Aborting."; exit 1; }
command -v scour >/dev/null 2>&1 || { echo >&2 "I require scour 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)"
BASE_DIR="$(dirname "${CURRENT_DIR}")"
ASSETS_DIR="${BASE_DIR}/assets"

OPTIPNG_OPTIONS="-preserve -quiet -o7"
ICON_SIZE=192

#######################################################

# Game images
AVAILABLE_GAME_IMAGES="
  button_back
  button_shuffle
  game_win
"

# Settings images
AVAILABLES_GAME_SETTINGS="
  difficulty:3x3,4x4,5x5
"

#######################################################

# optimize svg
function optimize_svg() {
  SOURCE="$1"

  cp ${SOURCE} ${SOURCE}.tmp
  scour \
      --remove-descriptive-elements \
      --enable-id-stripping \
      --enable-viewboxing \
      --enable-comment-stripping \
      --nindent=4 \
      --quiet \
      -i ${SOURCE}.tmp \
      -o ${SOURCE}
  rm ${SOURCE}.tmp
}

# build icons
function build_icon() {
  SOURCE="$1"
  TARGET="$2"

  echo "Building ${TARGET}"

  if [ ! -f "${SOURCE}" ]; then
    echo "Missing file: ${SOURCE}"
    exit 1
  fi

  optimize_svg "${SOURCE}"

  inkscape \
      --export-width=${ICON_SIZE} \
      --export-height=${ICON_SIZE} \
      --export-filename=${TARGET} \
      ${SOURCE}

  optipng ${OPTIPNG_OPTIONS} ${TARGET}
}

function build_settings_icons() {
  INPUT_STRING="$1"

  SETTING_NAME="$(echo "${INPUT_STRING}" | cut -d":" -f1)"
  SETTING_VALUES="$(echo "${INPUT_STRING}" | cut -d":" -f2 | tr "," " ")"

  for SETTING_VALUE in ${SETTING_VALUES}
  do
    SETTING_CODE="${SETTING_NAME}_${SETTING_VALUE}"
    build_icon ${CURRENT_DIR}/${SETTING_CODE}.svg ${ASSETS_DIR}/icons/${SETTING_CODE}.png
  done
}

#######################################################

# Create output folders
mkdir -p ${ASSETS_DIR}/icons

# Delete existing generated images
find ${ASSETS_DIR}/icons -type f -name "*.png" -delete

# build game images
for GAME_IMAGE in ${AVAILABLE_GAME_IMAGES}
do
  build_icon ${CURRENT_DIR}/${GAME_IMAGE}.svg ${ASSETS_DIR}/icons/${GAME_IMAGE}.png
done

# build settings images
for GAME_SETTING in ${AVAILABLES_GAME_SETTINGS}
do
  build_settings_icons "${GAME_SETTING}"
done
