#!/bin/bash -e
#
# format-and-check perform various cleanup and checks on the ATS.

errors=0

# error reports and counts errors
function error() {
	errors=$((errors+1))
	echo 1>&2 "error: $@"
}


echo "Removing dot-files..."
find ATS -name ".*" -print0 | xargs -0 rm -rfv

echo "Fixing permissions..."
find ATS -type f -print0 | xargs -0 chmod 664
find ATS -type d -print0 | xargs -0 chmod 775

echo "Looking for unknown file types..."
while IFS= read -r -d $'\0' file; do
	error "unknown file type: $file"
done < <(find ATS -type f ! -name "*.xml" -a ! -name "*.xsd" -a ! -name "*.ttcn" -a -name "*.json" -a -name "NOTES")

echo "Converting Windows line endings to Unix..."
find ATS -type f -name \*.ttcn -print0 | xargs -0 dos2unix 1>/dev/null

echo "Removing trailing whitespace"
find ATS -type f -name \*.ttcn -print0 | xargs -0 sed -i 's/[[:space:]]*$//'

echo "Linting TTCN-3 files..."
while IFS= read -r -d $'\0' file; do
	name=$(basename "$file" .ttcn)

	: Verify that the file path only contains valid characters.
	if ! [[ ${file%.ttcn} =~ [A-Za-z0-9_/]+ ]]; then
		error "invalid characters in file path: $file"
	fi

	: Verify that the module prefix is valid.
	if ! [[ $name =~ ^(Sem_|NegSem_|Syn_|NegSyn_|Pos_|Neg_) ]]; then
		error "invalid module prefix: $file"
	fi

	# TODO(simonm): Verify that the file name is the same as the module name.
	# TODO(simonm): Verify that required tags are present and well formed.
	# TODO(simonm): Verify that the sections are correct in path and @purpose tags.

done < <(find ATS -type f -name \*.ttcn -print0)

echo "Done."
if [[ $errors -gt 0 ]]; then
	echo "Found $errors errors"
	exit 1
fi
