#!/bin/sh
#

if git rev-parse --verify HEAD >/dev/null 2>&1
then
 against=HEAD
else
 # Initial commit: diff against an empty tree object
 against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi

# disallow ALOGW and ALOGE
if git diff --cached | grep "^\(+\| +\)" | grep -w 'ALOG[WE]\(_IF\)\?' > /dev/null; then
  cat <<\EOF
ERROR: Attempt to add ALOGW or ALOGE. These should be used only if something
       is truly catastrophic to the running application. Use ALOGI for
       important errors, ALOGD for mundane errors, and ALOGV for unimportant
       logs (don't use ALOGV for errors so they can be debugged).

If you are confident that the following uses are justified, commit this change with

  git commit --no-verify

EOF
  git diff --cached --diff-filter AM --color -G 'ALOG[WE](_IF)?' -- | awk '
  BEGIN { found=0 }
  /^\033\[[0-9]+m(@@|\+\+\+|\-\-\-)/ {
    if (found) { print substr(chunk, 2); found=0; chunk="" }
    if (match($1, "[-+]")) { print }
    else { chunk="\n" $0 }
    next
  }
  /^\033\[[0-9]+m ?\+/ {
    if (match($0, "\\<(ALOG[WE](_IF)?)\\>")) {
      found=1;
      chunk=chunk "\n" gensub("\\<(ALOG[WE](_IF)?)\\>", "\033[7m\\1\033[27m", "g")
    } else {
      chunk=chunk "\n" $0
    }
    next
  }
  {
    chunk=chunk "\n" $0
  }
  END { if (found) { print substr(chunk, 2) } }
'
  exit 1
fi

# If there are whitespace errors, print the offending file names and fail.
exec git diff-index --check --cached $against --