#!/usr/bin/env bash

set -e

SCRIPTDIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPTDIR}/.validate"

modules_files=('man/go.mod' 'vendor.mod')
tidy_files=("${modules_files[@]}" 'man/go.sum' 'vendor.sum')
vendor_files=("${tidy_files[@]}" 'vendor/')

validate_tidy_modules() {
	# check that all go.mod files exist in HEAD; go.sum files are generated by 'go mod tidy'
	# so we don't need to check for their existence beforehand
	for f in "${modules_files[@]}"; do
		if [ ! -f "$f" ]; then
			echo >&2 "ERROR: missing $f"
			return 1
		fi
	done
	# run mod tidy
	./hack/vendor.sh tidy
	# check if any files have changed
	git diff --quiet HEAD -- "${tidy_files[@]}" && [ -z "$(git ls-files --others --exclude-standard)" ]
}

validate_vendor_diff() {
	# recreate vendor/
	./hack/vendor.sh vendor
	# check if any files have changed
	git diff --quiet HEAD -- "${vendor_files[@]}" && [ -z "$(git ls-files --others --exclude-standard)" ]
}

validate_vendor_license() {
	while IFS= read -r module; do
		test -d "vendor/$module" || continue
		if ! compgen -G "vendor/$module/*" | grep -qEi '/(LICENSE|COPYING)[^/]*$'; then
			echo >&2 "WARNING: could not find copyright information for $module"
		fi
	done < <(awk '/^# /{ print $2 }' vendor/modules.txt)
}

if validate_tidy_modules && validate_vendor_diff && validate_vendor_license; then
	echo >&2 'PASS: Vendoring has been performed correctly!'
else
	{
		echo 'FAIL: Vendoring was not performed correctly!'
		echo
		if [ -n "$(git ls-files --others --exclude-standard)" ]; then
			echo 'The following files are missing:'
			git ls-files --others --exclude-standard
			echo
		fi
		if [ -n "$(git diff --name-status HEAD -- "${vendor_files[@]}")" ]; then
			echo 'The following files changed during re-vendor:'
			git diff --name-status HEAD -- "${vendor_files[@]}"
			echo
		fi
		echo 'Please revendor with hack/vendor.sh'
		echo
		git diff --diff-filter=M -- "${vendor_files[@]}"
	} >&2
	exit 1
fi
