#!/bin/sh
#
# /etc/ports/drivers/git: git driver script for ports(8)
#

[ $# = 1 ] || { echo "usage: $0 <file>" >&2; exit 1; }
. "$1" || { echo "couldn't read $1" >&2 ; exit 1; }

if [ -z "$URL" ]; then
	echo "URL not set in '$1'" >&2
	exit 2
fi
if [ -z "$NAME" ]; then
	echo "NAME not set in '$1'" >&2
	exit 2
fi
if [ -z "$BRANCH" ]; then
	echo "BRANCH not set in '$1'" >&2
	exit 2
fi

REPOSITORY="$PORTS_DIR/$NAME"
# The following feature is explained in the Wiki page SettingUpAGitRepo.
if [ -n "$LOCAL_REPOSITORY" ]; then
	REPOSITORY="$LOCAL_REPOSITORY"
fi

echo "Fetching updates from $URL"
echo "Updating collection $NAME"

if [ -d "$REPOSITORY/.git" ]; then
	cd "$REPOSITORY"
	git checkout -q "$BRANCH"
	git fetch -q
	git diff --pretty=format: --name-status "$BRANCH" origin/"$BRANCH" | sed "s/M\t/ Edit /g; s/A\t/ Checkout /g; s/D\t/ Delete /g" | sort
	# git-checkout(1) should ensure the existence of an exclude file,
	# whose length needs to be saved to make this driver idempotent.
	IGNORE_DEFAULT=$(wc -l .git/info/exclude | cut -d " " -f 1)
	IGNORE_NOW=$(( IGNORE_DEFAULT+1 ))
	# assemble the list of possible pkgmk artifacts.
	cat ./*/.signature \
		| awk -v FS=" " '{ if (($1 == "SHA256") && ($2 !~ /.footprint|Pkgfile/)) {$0=gensub(/SHA256 \((.*)\).*/,"\\1",1); print} }' >> .git/info/exclude
	# ... in case the work directories appear in this ports tree ...
	grep -E '^\s*PKGMK_KEEP_WORK=(|.)yes' /etc/pkgmk.conf && keepwork=1
	# Note: don't bother to read the definition of PKGMK_KEEP_WORK from
	# /usr/bin/pkgmk too; changing the defaults there is unsupported.
	if [ "$keepwork" = 1 ]; then
		echo "work/" >> .git/info/exclude
	fi
	# ... in case the built packages also appear in this ports tree...
	COMPRESSION_MODE="gz"
	eval $(grep "^PKGMK_COMPRESSION_MODE=" /etc/pkgmk.conf | sed 's/^PKGMK_//')
	for portname in *; do
		[ -f "$portname"/Pkgfile ] && echo "${portname}*.pkg.tar.${COMPRESSION_MODE}" >> .git/info/exclude
	done
	# end pkgmk artifacts. Now they should be safe from git-clean(1).
	git clean -q -f
	git reset -q --hard origin/"$BRANCH"
	# reset the gitignore(5) file to its default, with the (possibly unwanted)
	# side effect: the next run of this driver will delete sources in the ports
	# tree that the master repo considers out of date. This behaviour avoids
	# the performance impact of a constantly-growing gitignore(5) file.
	sed -i "${IGNORE_NOW},$$d" .git/info/exclude
else
	git clone -q -b "$BRANCH" "$URL" "$REPOSITORY"
	ls -1 "$REPOSITORY" | sed "s/^/ Checkout /"
fi

echo "Finished successfully"