#!/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 goimports over the changed files.
echo "Running code format checks..."
format_failed=false
repo_loc_failed=false
if ! make static-checks; then
  echo "  Code formatting checks failed"
  format_failed=true
fi

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 [ "$filename" == "lib/apis/v3/zz_generated.deepcopy.go" ]; then
    continue
  fi
  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 $format_failed; then
  echo
  echo "Some files failed code formatting check.  Run "
  echo "  make format-code"
  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 || $format_failed; then
  echo
  exit 1
fi

# Remove the trap handler.
trap "" EXIT
