#!/usr/bin/env bash

err() { printf '%s\n' "$*" >&2; }

build_remote() { makepkg-podman "$@"; }
cleanup() { rm -f "$lockfile"; }

lock() {
	[[ -f "$lockfile" ]] && {
		printf 'Lockfile found: %s\n' "$lockfile" >&2
		return 1
	}

	echo $$ > "$lockfile"
	lock_pid=$(<"$lockfile")
	[[ $$ == "$lock_pid" ]] || return 1
}

# Ensure one instance
lockfile="$HOME/.cache/pkgbuilder/.lock"
lock || exit 1
trap cleanup EXIT

declare -A pkg_dests
source "$HOME/.config/pkgbuilder/config"

wrkdir="$HOME/.cache/pkgbuilder/repositories"
mkdir -p "$wrkdir"

set -- "${repos[@]}"
while (($#>1)); do
	pkg_repo=$2
	pkg_dest="${pkg_dests[$1]}"

	repo_name="${pkg_repo##*/}"
	repo_path="${pkg_repo##*://}"
	repo_local="$wrkdir/${repo_path%.git}"

	err "repo: $repo_local"
	err " - url: $pkg_repo"

	# Check if the repo already exists
	if ! [[ -d "$repo_local" ]]; then
		mkdir -p "$wrkdir/${repo_path%$repo_name}"
		git clone "$pkg_repo" "$repo_local"

		build_remote "$pkg_dest" "$pkg_repo"
	else
		git -C "$repo_local" remote update
		if git -C "$repo_local" status --porcelain -bu | grep -q behind; then
			build_remote "$pkg_dest" "$pkg_repo"
			git -C "$repo_local" pull
		fi
	fi

	shift 2
done