#!/bin/sh

for file in "$@"; do
	has_rev=0

	if grep -q PORTREVISION "$file"; then
		has_rev=1
	fi

	tempfile="${file}.bumprev$$"

	awk -v has_rev=$has_rev < "$file" > "$tempfile" '
		/PORTVERSION/ {
			print $0;
			if (has_rev == 0) {
				print "PORTREVISION?=	1";
			}

			next;
		}

		/PORTREVISION/ {
			start = match($0, "[0-9]+");

			if (start != 0) {
				len = length;
				stop = RLENGTH;

				if (stop == len-start+1) {
					remainder = "";
				} else {
					remainder = substr($0, start+stop, \
					    len-start-stop+2);
				}

				num = int(substr($0, start, stop)) + 1;
				printf "%s%d%s\n", substr($0, 0, start-1), \
				    num, remainder;
			} else {
				print "PORTREVISION?=	1";
			}

			next;
		}

		{
			print $0;
		}
	' && cp "$tempfile" "$file"
	rm "$tempfile"

done

