#!/bin/sh -efu

. gb-sh-functions

bloat=
if [ "$1" = '--bloat' ]; then
	bloat=1
	shift
fi

force=
if [ "$1" = '--force' ]; then
	force=1
	shift
fi

REPO_DIR="$1"
shift

. gb-sh-tmpdir
. gb-sh-rpmhdrcache

if [ -n "$bloat" ]; then
	# Temporary repo: disable bzip2, use 'xz --fast' mode.
	set -- --bloat --xz --no-bz2
	export XZ_OPT='--fast'
else
	# Final repo: need to scan for useful files.
	for arch in $GB_ARCH noarch; do
		gb-x-useful-files $(set +f && ls -d "$REPO_DIR"/$arch/RPMS.?*) >"$tmpdir"/useful-files.$arch ||
			echo 1 >>"$tmpdir"/FAIL &
	done
	wait
	if [ -s "$tmpdir"/FAIL ]; then
		exit 1
	fi
	set --
	for arch in $GB_ARCH noarch; do
		set -- "$@" "$tmpdir"/useful-files.$arch
	done
	LC_ALL=C sort -m -u -o "$tmpdir"/useful-files -- "$@"
	# By default, both xz and bzip2 should be enabled.
	set -- --useful-files="$tmpdir"/useful-files --no-scan \
		--changelog-since=2009-01-01 \
		--xz ${GB_REPO_OPT_BZ2:---bz2}
	export XZ_OPT='--lzma2=nice=128,depth=80,lc=4'
fi

mkdir -p "$HOME"/.cache/gen{pkg,src}list

label="${GB_REPO_LABEL:-$GB_REPO_NAME}"
description="${GB_REPO_DESCRIPTION:-ALT Linux $label}"
date_s="$(date +%s)"

for arch in $GB_ARCH noarch; do
	[ -d "$REPO_DIR/$arch" ] || continue

	# Arch packages haven't changed?
	maybe_unchanged=
	if [ -z "$force" -a -z "$bloat" ] && ! fgrep -qsx "$arch" plan/change-arch; then
		# But the result also depends on the list of useful-files,
		# which might have changed due to other architectures.
		maybe_unchanged='--maybe-unchanged'
	fi

	#GNUPGHOME=/usr/lib/girar-builder-keys
	comps="${GB_REPO_COMPONENT_NAMES-}"
	[ -n "$comps" ] ||
		comps="$(set +f && cd "$REPO_DIR/$arch" && ls -d RPMS.?* | sed 's/^RPMS\.//')"
	[ -n "$comps" ] || {
		echo 1 >>"$tmpdir"/FAIL
		continue
	}

	genbasedir "$@" $maybe_unchanged \
		--cachedir="$HOME"/.cache \
		--architecture="$arch" \
		--architectures="$GB_ARCH noarch" \
		--archive="${GB_REPO_ARCHIVE:-$description}" \
		--codename="${GB_REPO_CODENAME:-$date_s}" \
		--description="${GB_REPO_DESCRIPTION:-$description}" \
		--label="$label" \
		--origin="${GB_REPO_ORIGIN:-ALT Linux Team}" \
		--suite="${GB_REPO_SUITE:-$label}" \
		--version="${GB_REPO_VERSION:-$date_s}" \
		-s --default-key="$GB_REPO_SIGNER" \
		--topdir="$REPO_DIR" \
		--flat --no-oldhashfile --bz2only --mapi \
		$arch $comps ||
			echo 1 >>"$tmpdir"/FAIL &
done
wait
if [ -s "$tmpdir"/FAIL ]; then
	exit 1
fi
