#!/bin/sh
# conform-port-survey [-h] <portsdir> -- one line per port, key=value fields, read from the files
# of the tree and never from a build: Makefile, pkg/, files/.
# rc 0 done, 2 usage. Portable sh and awk, no make.
#   src=ours|fetched   ours = DISTFILES set empty; fetched = a tuple, SITES or MASTER_SITES
#   subs=<n>           subpackages of MULTI_PACKAGES, 1 without it
#   plist=<n> descr=<n> counts of the subpackages that own a PLIST / DESCR file
#   man=yes|no         a man page in files/ or named in a PLIST
#   confdoc=Yes|No     CONFORM_DOC, default Yes
#   permit=<text>      PERMIT_PACKAGE, last field, may hold blanks
PATH=/bin:/sbin:/usr/bin:/usr/sbin
set -u

usage() { echo "usage: conform-port-survey [-h] portsdir" >&2; }
while getopts h o; do
	case $o in
	h) usage; exit 0 ;;
	*) usage; exit 2 ;;
	esac
done
shift $((OPTIND - 1))
[ $# -eq 1 ] && [ -d "$1" ] || { usage; exit 2; }
root=${1%/}

for mk in "$root"/*/*/Makefile; do
	[ -f "$mk" ] || continue
	d=${mk%/Makefile}
	pkgpath=${d#"$root"/}
	# value of VAR (first plain assignment), tabs and blanks trimmed
	val() { awk -v v="$1" '$0 ~ "^" v "[ \t]*[?+]?=" { sub(/^[^=]*=[ \t]*/, ""); sub(/[ \t]+$/, ""); print; found = 1; exit } END { if (!found) exit 1 }' "$mk"; }
	subs=$(awk '/^MULTI_PACKAGES[ \t]*[?+]?=/ { on = 1 }
		on { n += gsub(/-[A-Za-z0-9_.+]+/, "&"); if ($0 !~ /\\[ \t]*$/) on = 0 }
		END { print n + 0 }' "$mk")
	[ "$subs" -gt 0 ] || subs=1
	multi=no; [ "$subs" -gt 1 ] || grep -q '^MULTI_PACKAGES' "$mk" && multi=yes
	if dist=$(val DISTFILES) && [ -z "$dist" ]; then src=ours
	elif grep -q -E '^(DIST_TUPLE|SITES|MASTER_SITES|GH_ACCOUNT|MODPY_PI)' "$mk"; then src=fetched
	else src=unknown; fi
	plist=$(find "$d/pkg" -maxdepth 1 -name 'PLIST*' 2>/dev/null | wc -l | tr -d ' ')
	descr=$(find "$d/pkg" -maxdepth 1 -name 'DESCR*' 2>/dev/null | wc -l | tr -d ' ')
	man=no
	if find "$d/files" -maxdepth 2 -name '*.[1-9]' 2>/dev/null | grep -q .; then man=yes
	elif grep -q -E '^man/man[1-9]/' "$d"/pkg/PLIST* 2>/dev/null; then man=yes; fi
	rev=no; grep -q '^REVISION' "$mk" && rev=yes
	user=no; grep -q -E '^@new(user|group)' "$d"/pkg/PLIST* 2>/dev/null && user=yes
	rc=no; find "$d/pkg" -maxdepth 1 -name '*.rc' 2>/dev/null | grep -q . && rc=yes
	confdoc=$(val CONFORM_DOC) || confdoc=Yes
	permit=$(val PERMIT_PACKAGE) || permit=unset
	echo "$pkgpath src=$src multi=$multi subs=$subs plist=$plist descr=$descr man=$man rev=$rev user=$user rc=$rc confdoc=$confdoc permit=$permit"
done
