#! /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

  build_icon ${CURRENT_DIR}/skins/${SKIN_CODE}/empty.svg      ${BASE_DIR}/assets/skins/${SKIN_CODE}_empty.png
  build_icon ${CURRENT_DIR}/skins/${SKIN_CODE}/good.svg       ${BASE_DIR}/assets/skins/${SKIN_CODE}_good.png
  build_icon ${CURRENT_DIR}/skins/${SKIN_CODE}/misplaced.svg  ${BASE_DIR}/assets/skins/${SKIN_CODE}_misplaced.png
  build_icon ${CURRENT_DIR}/skins/${SKIN_CODE}/wrong.svg      ${BASE_DIR}/assets/skins/${SKIN_CODE}_wrong.png
}

# Game icons
build_icon ${CURRENT_DIR}/button_back.svg   ${BASE_DIR}/assets/icons/button_back.png
build_icon ${CURRENT_DIR}/button_help.svg   ${BASE_DIR}/assets/icons/button_help.png
build_icon ${CURRENT_DIR}/button_start.svg  ${BASE_DIR}/assets/icons/button_start.png
build_icon ${CURRENT_DIR}/game_win.svg      ${BASE_DIR}/assets/icons/game_win.png
build_icon ${CURRENT_DIR}/key.svg           ${BASE_DIR}/assets/icons/key.png

build_icon ${CURRENT_DIR}/lang_fr.svg       ${BASE_DIR}/assets/icons/lang_fr.png
build_icon ${CURRENT_DIR}/length_5.svg      ${BASE_DIR}/assets/icons/length_5.png

# Skins
build_icon_for_skin "default"
