#!/bin/bash

. "$(dirname "$(readlink -e "$0")")/config"
. "$(dirname "$(readlink -e "$0")")/db-functions"

if [ $# -lt 3 ]; then
	msg "usage: %s <repo> <arch> <pkgfile> ..." "${0##*/}"
	exit 1
fi

repo="$1"
arch="$2"
pkgfiles=("${@:3}")

ftppath="$FTP_BASE/$repo/os"

if ! check_repo_permission "$repo"; then
	die "You don't have permission to add packages to %s" "${repo}"
fi

if [ "$arch" == "any" ]; then
	tarches=("${ARCHES[@]}")
else
	tarches=("$arch")
fi

for tarch in "${tarches[@]}"; do
	repo_lock "$repo" "$tarch" || exit 1
done

for tarch in "${tarches[@]}"; do
	for pkgfile in "${pkgfiles[@]}"; do
		if [[ ! -f "${FTP_BASE}/${repo}/os/${arch}/${pkgfile##*/}" ]]; then
			die "Package file %s not found in %s" "${pkgfile##*/}" "${FTP_BASE}/${repo}/os/${arch}/"
		else
			msg "Adding %s to [%s]..." "$pkgfile" "$repo"
		fi
	done
	arch_repo_add "${repo}" "${tarch}" "${pkgfiles[@]}"
	repo_unlock "$repo" "$tarch"
done