#! /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}")"

OPTIPNG_OPTIONS="-preserve -quiet -o7"

# 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 \
      -i ${SOURCE}.tmp \
      -o ${SOURCE}
  rm ${SOURCE}.tmp
}

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

  optimize_svg "${SOURCE}"

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

  optipng ${OPTIPNG_OPTIONS} ${TARGET}
}

function build_icon_for_skin() {
  SKIN_CODE="$1"

  build_icon ${CURRENT_DIR}/skin_${SKIN_CODE}.svg ${BASE_DIR}/assets/icons/skin_${SKIN_CODE}.png
  for VALUE in {1..9};
  do
    build_icon ${CURRENT_DIR}/skins/${SKIN_CODE}/${VALUE}.svg ${BASE_DIR}/assets/skins/${SKIN_CODE}_${VALUE}.png
  done
}

# Game icons
build_icon ${CURRENT_DIR}/button_start.svg ${BASE_DIR}/assets/icons/button_start.png
build_icon ${CURRENT_DIR}/difficulty_easy.svg ${BASE_DIR}/assets/icons/difficulty_easy.png
build_icon ${CURRENT_DIR}/difficulty_medium.svg ${BASE_DIR}/assets/icons/difficulty_medium.png
build_icon ${CURRENT_DIR}/difficulty_hard.svg ${BASE_DIR}/assets/icons/difficulty_hard.png
build_icon ${CURRENT_DIR}/size_2.svg ${BASE_DIR}/assets/icons/size_2.png
build_icon ${CURRENT_DIR}/size_3.svg ${BASE_DIR}/assets/icons/size_3.png
build_icon ${CURRENT_DIR}/skins/empty.svg ${BASE_DIR}/assets/skins/empty.png

# Skins
build_icon_for_skin "default"
build_icon_for_skin "food"
build_icon_for_skin "nature"
