#!/usr/bin/env bash

help="
Usage:
  -i    Inplace edit files.

Example:
  $ ./tools/clang-format -i
"

inplace='NO'
while [ $# -gt 0 ]; do
  case "$1" in
    -i)
      inplace='YES'
      ;;
    --help)
      printf "$help"
      exit
      ;;
    -h)
      printf "$help"
      exit
      ;;
    -*)
      echo "Illegal option $1"
      ;;
  esac
  shift $(( $# > 0 ? 1 : 0 ))
done

cmd=`command -v clang-format-8`
if test -z "$cmd"; then
  cmd=`command -v clang-format`
fi

command $cmd --version

if test $inplace = 'YES'; then
  find packages client/c -iname *.h -o -iname *.cc -o -iname *.c | xargs $cmd -style=file -i
fi

rep_count=`find packages client/c -iname *.h -o -iname *.cc -o -iname *.c | xargs $cmd -style=file -output-replacements-xml | grep -c '<replacement '`

if ! test $rep_count = 0; then
  find packages client/c -iname *.h -o -iname *.cc -o -iname *.c | xargs $cmd -style=file
  exit 1
fi
