#!/bin/sh -efu

. gb-sh-functions

arch="$1"; shift
[ -s plan/arepo-add-$arch -o -s plan/arepo-rm-$arch ] || exit 0

comp=${GB_AREPO_COMPONENT_NAME:-$GB_REPO_FLAVOUR}

commit()
{
	while read -r F; do
		RM $GB_REPO_DIR/$arch/RPMS.$comp/$F
		if use_repo_files; then
			RM $GB_REPO_DIR/files/$arch/RPMS/$F
		fi
	done < plan/arepo-rm-$arch

	while read -r N EVR F dummy; do
		if use_repo_files; then
			CP arepo/$arch/rpms/$F $GB_REPO_DIR/files/$arch/RPMS/$F
			LN ../../files/$arch/RPMS/$F $GB_REPO_DIR/$arch/RPMS.$comp/$F
		else
			CP arepo/$arch/rpms/$F $GB_REPO_DIR/$arch/RPMS.$comp/$F
		fi
	done < plan/arepo-add-$arch
}

RM()
{
	if ! [ -f "$1" ]; then
		echo "$1: file not found"
		return 1
	fi >&2
}

CP()
{
	if [ -e "$2" ] || [ -L "$2" ]; then
		echo "$2: file already exists"
		return 1
	fi >&2
}

LN()
{
	if [ -e "$2" ] || [ -L "$2" ]; then
		echo "$2: file already exists"
		return 1
	fi >&2
}

# test commit
commit

RM()
{
	rm -v -f "$1"
}

CP()
{
	cp -v -l "$1" "$2" 2>/dev/null || cp -v "$1" "$2"
}

LN()
{
	ln -v -s "$1" "$2"
	if ! [ -f "$2" ]; then
		echo "$2: created dangling symlink"
		rm -v "$2"
		return 1
	fi >&2
}

# real commit
commit > logs/commit-$arch.log

install -pm644 -- plan/arepo-table-$arch \
	"$GB_REPO_DIR/files/list/arepo-$arch.list"

rsync -rlt --no-times --no-perms --no-owner --no-group arepo/$arch/base/ "$GB_REPO_DIR"/$arch/base/

stamp_echo >&2 "[$arch] update OK"
