#! /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"
ICON_SIZE=192

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

# Game images
AVAILABLE_GAME_IMAGES="
  button_back
  button_start
  game_fail
  game_win
  level_easy
  level_normal
  level_hard
  level_nightmare
"

# Skins
AVAILABLE_SKINS="
  retro
  colors
"

# Images per skin
SKIN_IMAGES="
  empty
  head
  body
  fruit
"

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

# 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}"
  fi

  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"

  # skin main image
  build_icon ${CURRENT_DIR}/skin_${SKIN_CODE}.svg ${BASE_DIR}/assets/icons/skin_${SKIN_CODE}.png

  # skin images
  for SKIN_IMAGE in ${SKIN_IMAGES}
  do
    build_icon ${CURRENT_DIR}/skins/${SKIN_CODE}/${SKIN_IMAGE}.svg ${BASE_DIR}/assets/skins/${SKIN_CODE}_${SKIN_IMAGE}.png
  done
}

mkdir -p ${BASE_DIR}/assets/icons
mkdir -p ${BASE_DIR}/assets/skins

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

# build skins images
for SKIN in ${AVAILABLE_SKINS}
do
  build_icon_for_skin "${SKIN}"
done
