#!/usr/bin/env bash
set -euo pipefail

ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
SOURCE="$ROOT/priv/static/images/logo.svg"
TMP_DIR=$(mktemp -d)

cleanup() {
  rm -rf "$TMP_DIR"
}
trap cleanup EXIT

for command_name in inkscape magick; do
  if ! command -v "$command_name" >/dev/null 2>&1; then
    echo "Required command is unavailable: $command_name" >&2
    exit 1
  fi
done

render_square() {
  local size=$1
  local artwork_size=$2
  local destination=$3

  magick \
    -size "${size}x${size}" \
    xc:'#F7F7F5' \
    \( "$TMP_DIR/mark-1024.png" -resize "${artwork_size}x${artwork_size}" \) \
    -gravity center \
    -composite \
    -alpha on \
    -depth 8 \
    -strip \
    "PNG32:$destination"
}

mkdir -p \
  "$ROOT/android/store-assets" \
  "$ROOT/android/app/src/main/res/mipmap-mdpi" \
  "$ROOT/android/app/src/main/res/mipmap-hdpi" \
  "$ROOT/android/app/src/main/res/mipmap-xhdpi" \
  "$ROOT/android/app/src/main/res/mipmap-xxhdpi" \
  "$ROOT/android/app/src/main/res/mipmap-xxxhdpi"

inkscape \
  "$SOURCE" \
  --export-type=png \
  --export-filename="$TMP_DIR/mark-1024.png" \
  --export-width=1024 \
  --export-height=1024

magick "$TMP_DIR/mark-1024.png" -resize 48x48 -alpha on -depth 8 -strip \
  "PNG32:$ROOT/priv/static/images/favicon-48.png"
magick "$TMP_DIR/mark-1024.png" -resize 192x192 -alpha on -depth 8 -strip \
  "PNG32:$ROOT/priv/static/images/pwa-192.png"
magick "$TMP_DIR/mark-1024.png" -resize 512x512 -alpha on -depth 8 -strip \
  "PNG32:$ROOT/priv/static/images/pwa-512.png"
magick "$TMP_DIR/mark-1024.png" -define icon:auto-resize=48,32,16 \
  "$ROOT/priv/static/favicon.ico"

render_square 512 300 "$ROOT/priv/static/images/pwa-maskable-512.png"
render_square 1024 600 "$ROOT/priv/static/images/pwa-maskable-1024.png"
render_square 180 106 "$ROOT/priv/static/images/apple-touch-icon.png"
render_square 1024 600 "$ROOT/priv/static/images/app-icon-1024.png"
render_square 512 300 "$ROOT/android/store-assets/icon-512.png"

render_square 48 28 "$ROOT/android/app/src/main/res/mipmap-mdpi/ic_launcher.png"
render_square 72 42 "$ROOT/android/app/src/main/res/mipmap-hdpi/ic_launcher.png"
render_square 96 56 "$ROOT/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png"
render_square 144 84 "$ROOT/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png"
render_square 192 112 "$ROOT/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png"

echo "Generated web, PWA, store, and legacy Android brand assets from $SOURCE"
