#!/usr/bin/env bash

set -eu -o pipefail

declare skip=false

declare -a compress=()
declare -a optimize=()

declare -a files=()

# The version of copypng shipped with Xcode creates iPhone-optimized PNGs by default. This implementation does not.
# - It’s an undocumented extension. While some work has been done reverse-engineering it, support for writing it is not
#   widespread. In particular, neither oxipng nor upstream pngcrush support writing it;
# - It’s apparently considered deprecated. See: https://github.com/w3c/png/issues/45#issuecomment-3489696077; and
# - It may not even be better for application performance. See: https://imageoptim.com/tweetbot.html.

for arg in "$@"; do
  case "$arg" in
    -strip-PNG-text)
      optimize=('--strip' 'tEXt,iTXt,zTXt')
      if [[ "${#compress[@]}" == 0 ]]; then
          compress=('--nx' '--nz')
      fi
      ;;
    -skip-PNGs)
      skip=true
      ;;
    -compress)
      compress=('-o' 'max')
      ;;
    "")
      # Sometimes xcbuild passes empty arguments
      ;;
    -*)
      printf "%s" "WARNING: Ignoring unknown option $arg"
      ;;
    *)
      files+=("$arg")
      ;;
  esac
done

if [[ "${#compress[@]}" == 0 ]]; then
    skip=true
fi

case "${#files[@]}" in
  0)
    @echo@ "ERROR: Can't find"
    exit 1
    ;;
  1)
    @echo@ "ERROR: Destination file missing"
    exit 1
    ;;
  2)
    source=${files[0]}
    dest=${files[1]}
    ;;
  *)
    source=${files[0]}
    dest=${files[1]}
    ;;
esac

# Apple’s `copypng` appears to ignore any flags and will only copy files with bit depths other than 8-bit.
# This is included to be compatible, but maybe we should have a flag to optimize them anyway.
if [[ "${XCODE_HIGH_BIT_DEPTH_COMPAT:-0}" == "1" && ! $(@file@ "$source") =~ 8-bit ]]; then
    @echo@ 'libpng warning: Warning: Input PNG does not have an 8 bit input depth.  Please convert your PNG to 8-bit for optimal performance on iPhone OS.'
    skip=true
fi

if $skip; then
  @cp@ "$source" "$dest"
else
  @oxipng@ --quiet "${compress[@]}" "${optimize[@]}" "$source" --force --out "${dest[@]}"
fi
