#!/usr/bin/env bash

# repo_build.sh
# Script to create a signed Arch Linux repository
# Usage: ./repo_build.sh [dir] [path-to-db] [key-id]

cd "$(dirname "$0")"

TARGET="${1-arch}"
DB_FILE="${2-slonkrepo.db.tar.xz}"
KEY_ID="${3-9C51F3072F8D11A2}"

echo_stderr() {
	echo $@ >&2
}

if [[ ! -d "${TARGET}" ]]; then
	echo_stderr "Error: Not a directory: ${TARGET}"
	exit 1
fi

for dir in "${TARGET}" "${TARGET}"/*; do
	[[ ! -d "${dir}" ]] &&continue
	echo_stderr "Processing '${dir}'"
	cd "${dir}"
	packages=()
	for file in *.pkg*; do
		[[ "${file}" == '*.pkg*' ]] && continue
		[[ "${file}" =~ .*'.sig' ]] && continue
		packages+=("${file}")
		[[ -f "${file}.sig" ]] && continue
		echo_stderr "Signing '${file}'"
		if gpg -u "${KEY_ID}" --output "${file}.sig" --detach-sig "${file}"; then
			echo_stderr "Signed '${file}'"
		else
			code=$?
			echo_stderr "gpg failed with exit code ${code}."
			exit $code
		fi
	done
	if [[ "${#packages}" == 0 ]]; then
		echo_stderr "No packages in '${dir}', ignoring"
		cd - >/dev/null
		continue
	fi
	if repo-add -n -s -k "${KEY_ID}" "${DB_FILE}" "${packages[@]}"; then
		echo_stderr "Processed '${dir}'"
	else
		code=$?
		echo_stderr "repo-add failed with exit code ${code}."
		exit $code
	fi
	cd - >/dev/null
done

echo_stderr "All done"