#!/bin/bash

set -e

# Make sure we get some output if an unexpected command happens to fail.
trap "echo git pre-commit hook failed." EXIT

# Redirect output to stderr.
exec 1>&2

changed_files=$(git diff --cached --name-only)
changed_go_files=$(git diff --cached --name-only | grep -E '.go$' || true)
all_go_files=$(find -name '*.go' | grep -v /vendor/)

copyright_check_failed=false
copyright_owner="Tigera, Inc"

[ -f "git-hooks/settings.sh" ] && source "git-hooks/settings.sh"

# Run go fmt over the changed files.
echo "Checking changed files with gofmt..."
gofmt_failed=false
repo_loc_failed=false
for filename in $changed_go_files; do
  if [ ! -e "${filename}" ]; then
    continue;
  fi
  if gofmt -d "${filename}" | grep '.'; then
    echo "  gofmt would make changes to file:" ${filename}
    gofmt_failed=true
  fi
done

echo "Checking repo location..."
for filename in $all_go_files; do
  if grep -q 'tigera/libcalico-go' "${filename}"; then
    echo "  File refers to old libcalico-go repo location:" ${filename}
    repo_loc_failed=true
  fi
done

# Check copyright statement has been updated.
echo "Checking changed files for copyright statements..."
year=$(date +'%Y')
copyright_re="Copyright \(c\) .*${year}.* ${copyright_owner}\. All rights reserved\."

for filename in $changed_go_files; do
  if [ -e "${filename}" ] && ! grep -q -E "$copyright_re" "${filename}"; then
    echo "  Changed file is missing Tigera copyright:" ${filename}
    copyright_check_failed=true
  fi
done

if $gofmt_failed; then
  echo
  echo "Some files failed gofmt check. Run"
  echo "  go fmt \$(go list ./...)"
  echo "to format all files."
fi

if $copyright_check_failed; then
  echo
  echo "Copyright statement should match"
  echo "  ${copyright_re}"
  echo "Example for new files:"
  echo "  Copyright (c) ${year} ${copyright_owner}. All rights reserved."
  echo "Example for updated files (use commas and year ranges):"
  echo "  Copyright (c) 2012,2015-${year} ${copyright_owner}. All rights reserved."
  echo "Change expected copyright owner by creating git-hooks/settings.sh."
fi

if $repo_loc_failed; then
  echo
  echo "Found old tigera/libcalico-go repo location.  Should be"
  echo "projectcalico/libcalico-go."
fi

if $copyright_check_failed || $repo_loc_failed || $gofmt_failed; then
  echo
  exit 1
fi

# Remove the trap handler.
trap "" EXIT
