#! /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 "$(dirname "${CURRENT_DIR}")")"
ASSETS_DIR="${BASE_DIR}/assets"

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

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

# Game images (svg files found in `images` folder)
AVAILABLE_GAME_IMAGES=""
if [ -d "${CURRENT_DIR}/images" ]; then
  AVAILABLE_GAME_IMAGES="$(find "${CURRENT_DIR}/images" -type f -name "*.svg" | awk -F/ '{print $NF}' | cut -d"." -f1 | sort)"
fi

# Skins (subfolders found in `skins` folder)
AVAILABLE_SKINS=""
if [ -d "${CURRENT_DIR}/skins" ]; then
  AVAILABLE_SKINS="$(find "${CURRENT_DIR}/skins" -mindepth 1 -type d | awk -F/ '{print $NF}')"
fi

# Images per skin (svg files found recursively in `skins` folder and subfolders)
SKIN_IMAGES=""
if [ -d "${CURRENT_DIR}/skins" ]; then
  SKIN_IMAGES="$(find "${CURRENT_DIR}/skins" -type f -name "*.svg" | awk -F/ '{print $NF}' | cut -d"." -f1 | sort | uniq)"
fi

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

# 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_image() {
  SOURCE="$1"
  TARGET="$2"

  echo "Building ${TARGET}"

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

  optimize_svg "${SOURCE}"

  mkdir -p "$(dirname "${TARGET}")"

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

  optipng ${OPTIPNG_OPTIONS} "${TARGET}"
}

function build_image_for_skin() {
  SKIN_CODE="$1"

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

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

# Delete existing generated images
if [ -d "${ASSETS_DIR}/ui" ]; then
  find ${ASSETS_DIR}/ui -type f -name "*.png" -delete
fi
if [ -d "${ASSETS_DIR}/skins" ]; then
  find ${ASSETS_DIR}/skins -type f -name "*.png" -delete
fi

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

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

