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

SOURCE="${CURRENT_DIR}/icon.svg"
SOURCE_FASTLANE="${CURRENT_DIR}/featureGraphic.svg"

OPTIPNG_OPTIONS="-preserve -quiet -o7"

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

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

# optimize svg
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() {
  ICON_SIZE="$1"
  TARGET="$2"

  echo "Building ${TARGET}"

  TARGET_PNG="${TARGET}.png"

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

  optipng ${OPTIPNG_OPTIONS} ${TARGET_PNG}
}

# build fastlane image
function build_fastlane_image() {
  WIDTH="$1"
  HEIGHT="$2"
  TARGET="$3"

  echo "Building ${TARGET}"

  cp ${SOURCE_FASTLANE} ${SOURCE_FASTLANE}.tmp
  scour \
      --remove-descriptive-elements \
      --enable-id-stripping \
      --enable-viewboxing \
      --enable-comment-stripping \
      --nindent=4 \
      --quiet \
      -i ${SOURCE_FASTLANE}.tmp \
      -o ${SOURCE_FASTLANE}
  rm ${SOURCE_FASTLANE}.tmp

  TARGET_PNG="${TARGET}.png"

  inkscape \
      --export-width=${WIDTH} \
      --export-height=${HEIGHT} \
      --export-filename=${TARGET_PNG} \
      ${SOURCE_FASTLANE}

  optipng ${OPTIPNG_OPTIONS} ${TARGET_PNG}
}

build_icon  72 ${BASE_DIR}/android/app/src/main/res/mipmap-hdpi/ic_launcher
build_icon  48 ${BASE_DIR}/android/app/src/main/res/mipmap-mdpi/ic_launcher
build_icon  96 ${BASE_DIR}/android/app/src/main/res/mipmap-xhdpi/ic_launcher
build_icon 144 ${BASE_DIR}/android/app/src/main/res/mipmap-xxhdpi/ic_launcher
build_icon 192 ${BASE_DIR}/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher
build_icon 512 ${BASE_DIR}/fastlane/metadata/android/en-US/images/icon

build_fastlane_image 1024 500 ${BASE_DIR}/fastlane/metadata/android/en-US/images/featureGraphic
