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

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

# Menu images
AVAILABLE_MENU_IMAGES="
demo
"

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

# 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

  if [[ ! -d "$(dirname ${TARGET})" ]]; then
    mkdir -p "$(dirname ${TARGET})"
  fi

  optimize_svg "${SOURCE}"

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

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

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

# Create output folders
mkdir -p "${ASSETS_DIR}"

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

# build menu images
for MENU_IMAGE in ${AVAILABLE_MENU_IMAGES}; do
  build_icon "${CURRENT_DIR}/menu_${MENU_IMAGE}.svg" "${ASSETS_DIR}/menu/${MENU_IMAGE}.png"
done
