#!/bin/sh
#
# heic2jpg - convert heic to jpg
# dependencies: sips(1)

set -eu

case "$(uname)" in
  Darwin)
    if [ "$#" -eq 1 ]; then
      readonly filename="$1"
      sips -s format jpeg "${filename}" --out "${filename%.*}.jpg"
      exit
    fi
    if [ "$#" -eq 0 ]; then
      # no arguments provided, find all .heic or .HEIC files
      files=$(find . -type f \( -iname '*.heic' -o -iname '*.HEIC' \))
    else
      # arguments provided, use those as file names
      files="$*"
    fi

    for i in ${files}; do
      fileNoExt="${i%.*}"
      jpgFile="${fileNoExt}_heic_conv.jpg"

      # formatOptions: low, normal, high or best
      sips -s format jpeg -s formatOptions high "${i}" --out "${jpgFile}"
      touch -r "${i}" "${jpgFile}"
      rm -- "${i}"
    done
    ;;
  *)
    os="$(uname)"
    printf '%s\n' "${0##*/}: sips command is not available on ${os}" >&2
    exit 1
    ;;
esac
