#!/bin/sh

export readonly PORTSDIR=${PORTSDIR:-/usr/ports}

readonly hunspell="hunspell -d en_US"

skip_spellcheck=0 # skip spellchecking of descrption/message files

display_usage() {
	<< EOF >&2 cat
Usage: ${0##*/} -h
       ${0##*/} [-s]

    -h - show this help
    -s - skip spellcheck

EOF
	exit 1
}

reinplace_file() {
	local file=$1 expr=$2

	[ "$expr" ] || return
	sed -E "$expr" "$file" > "$file.new"
	mv "$file.new" "$file"
}

while getopts "hs" option; do
	case $option in
	s)
		skip_spellcheck=1 ;;
	*)
		display_usage
	esac
done

if [ ! "$(make -V PKGNAME 2>/dev/null)" ]; then
	echo "===> This is not port directory" >&2
	exit 1
fi

descr_file=$(make -V DESCR)
flavors=$(make -V FLAVORS | sed 's,^ ,,')
if [ "$flavors" ]; then
	for f in $flavors; do
		wrkdirs="$wrkdirs|$(basename "$(make FLAVOR=$f -V WRKDIR)")"
	done
else
	wrkdirs="|work"
fi

rej_files=$(find -E . -name "*.rej" ! -regex "\./(\.svn$wrkdirs)/.*")
if [ "$rej_files" ]; then
	echo "===> Found rejected patch file(s)" >&2
	echo " $rej_files" | sed 's|./||g' >&2
	exit 1
fi

find -E . \( -name "*.orig" -or -size 0 \) ! -regex "\./(\.svn$wrkdirs)/.*" -delete
if [ $skip_spellcheck -eq 0 ]; then
	if which hunspell >/dev/null; then
		[ -f "$descr_file" ] && $hunspell "$descr_file"
		[ -f pkg-message ] && $hunspell pkg-message
		[ -f files/pkg-message.in ] && $hunspell files/pkg-message.in
	else
		echo "===> Hunspell not found, skipping spellcheck"
	fi
fi

find -E . -type f ! -regex "\./(\.svn$wrkdirs)/.*" | while read file; do
	if ! tail -n 1 "$file" | tr '\n' '~' | grep -q '~$'; then
		echo >> "$file"
		echo "===> Added final newline to ${file##./}"
	fi
done

comment=$(make -V COMMENT)
if echo "$comment" | grep -Eq '^(A|An) '; then
	new_comment=$(echo "$comment" | awk '{
		gsub("^(A|An) ", "", $0);
		print toupper( substr($0, 1, 1) ) substr($0, 2);
	}')
	sed_expr="s|^COMMENT=.*|COMMENT=	$new_comment|"
	echo "===> Removed leading article from COMMENT"
fi
reinplace_file Makefile "$sed_expr"

if [ -f "$descr_file" ]; then
	sed_expr=""
	if grep -q '^Author:' "$descr_file"; then
		sed_expr="/^Author:/d;"
		echo "===> Deleting Author: line from description file"
	fi

	if grep -Eq '^WWW:(	| {2,})' "$descr_file"; then
		sed_expr="$sed_expr s#^WWW:(	| {2,})#WWW: #g;"
		echo "===> Fixing WWW: line in description file"
	fi
	reinplace_file "$descr_file" "$sed_expr"
else
	echo "===> Port's description file is missing"
fi

if which portlint >/dev/null; then
	echo "===> Portlint output:"
	portlint -abt
else
	echo "===> Portlint not found, skipping port checks"
fi

[ "$flavors" ] && echo "===> Flavors: $flavors"
bdeps=$(pfind -b $(make -V PORTNAME) | awk 'END {print NR}')
[ $bdeps -gt 0 ] && echo "===> Port is build dependency for $bdeps port(s)"

slaves=$(pfind -s "$(make -V CATEGORIES | \
	awk '{print $1}')/$(basename "$PWD")" | cut -f1 -d' ' 2>/dev/null)
if [ "$slaves" ]; then
	echo "===> Found slave ports:"
	echo "$slaves"
fi
