#!/usr/bin/env -S sh
# SPDX-FileCopyrightText: 2024 Lady <https://www.ladys.computer/about/#lady>
# SPDX-License-Identifier: MPL-2.0

# This Source Code Form is subject to the terms of the Mozilla Public License, v 2.0.
# If a copy of the M·P·L was not distributed with this file, You can obtain one at <https://mozilla.org/MPL/2.0/>.

IGNORE_PATTERN='README\..*|LICENSES/.*|post-receive'
LIVE_BRANCH=live

if grep -q " refs/heads/$LIVE_BRANCH"
then
	# Live branch was updated; copy resulting files.
	#
	# This isn’t super robust; if there is a failure partway thru then
	# some files will be old and some will be new.
	hashfiles=$(git ls-tree -rz "$LIVE_BRANCH" | tr '\000\t' '\n;' | sed 's/^[^ ]* [^ ]* //')
	files=$(printf '%s' "$hashfiles" | sed 's|.*;|/var/www/gitweb/|')
	existings=$(find /var/www/gitweb -type f)

	echo '`'"$LIVE_BRANCH"'´ was updated; updating files…'

	while test -n "$hashfiles"
	do
		# Iterate over each file and extract it into the appropriate
		# location.
		hashfile=$(printf '%s' "$hashfiles" | head -n 1)
		hash=$(printf '%s\n' "$hashfile" | sed 's/;.*//')
		file=$(printf '%s\n' "$hashfile" | sed 's|.*;|/var/www/gitweb/|')
		dir=$(printf '%s\n' "$file" | sed 's|[^/]*$||')

		if test '!' -d "$dir"
		then
			# The containing directory does not exist yet.
			mkdir -p "$dir"
		fi

		if printf '%s\n' "$file" | grep -E -q '^/var/www/gitweb/('"$IGNORE_PATTERN"')$'
		then
			# The current file matches the ignore pattern.
			:
		else
			# The current file does not match the ignore pattern.
			printf 'Updating <%s>…\n' "$file"
			git cat-file blob "$hash" > "$file"
		fi

		hashfiles=$(printf '%s' "$hashfiles" | tail -n +2)
	done

	while test -n "$existings"
	do
		# Iterate over existing files and remove ones which aren’t in the
		# repo.
		existing=$(printf '%s' "$existings" | head -n 1)
		if printf '%s' "$files" | grep -F -q -x "$existing"
		then
			# The file matches a file in the repo.
			:
		else
			# The file does not match a file in the repo.
			printf 'Removing <%s>…\n' "$file"
			rm "$existing"
		fi
		existings=$(printf '%s' "$existings" | tail -n +2)
	done
fi