#!/usr/bin/env bash

# Verify that tracked Go test files use external test packages.

# Exit on first failure.
set -e

# Exit on unset variable.
set -u

# Change directory to repository root.
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
readonly SCRIPT_DIR
cd "${SCRIPT_DIR}/.."

success=0

while read -r filepath; do
  # Skip files that Git tracks but are pending deletion in the workspace.
  if [[ ! -f "${filepath}" ]]; then
    continue
  fi

  package_name="$(
    awk '/^package[[:space:]]+/ { print $2; exit }' "${filepath}"
  )"

  if [[ -z "${package_name}" ]]; then
    printf 'Test file is missing a package declaration: %s\n' "${filepath}" >&2
    success=255
    continue
  fi

  if [[ ! "${package_name}" =~ _test$ ]]; then
    printf \
      'Test file must declare a package ending in _test: %s declares %s\n' \
      "${filepath}" \
      "${package_name}" >&2
    success=255
  fi
done < <(git ls-files -- '*_test.go')

exit "${success}"
