#!/usr/bin/env bash
set -e

STAGED=$(
  git --no-pager diff --name-only --no-color --cached --diff-filter=d |
    # Remove quotations used to surrounding filenames with special characters.
    sed -e "s/^\"//" -e "s/\"$//g"
)

MIX_TARGETS=()
WEB_TARGETS=()
while IFS= read -r FILENAME
do
  if [[ "$FILENAME" =~ .*\.exs? ]]; then
    MIX_TARGETS+=("$FILENAME")
  elif [[ "$FILENAME" =~ .*\.jsx? ]] || [[ "$FILENAME" =~ .*\.tsx? ]]; then
    WEB_TARGETS+=("$FILENAME")
  fi
done <<< "$STAGED"

if (( ${#MIX_TARGETS[@]} )); then
  mix format "${MIX_TARGETS[@]}"
  git add "${MIX_TARGETS[@]}"
fi

if (( ${#WEB_TARGETS[@]} )); then
  prettier --write "${WEB_TARGETS[@]}"
  git add "${WEB_TARGETS[@]}"
fi