#!/bin/sh

TARGETS="${TARGETS:-"orgs:snailed users:luca"}"
API_URL="${API_URL:-"https://git.snaile.de/api/v1"}"
ENDPOINT="${ENDPOINT:-"repos"}"
FILTER="${FILTER:-".[].ssh_url"}"
COMMAND="${COMMAND:-"git clone --recursive -j8"}"
TOKEN="${TOKEN:-"$(secret-tool lookup gitea api_token)"}"
# NOTE: Store with `secret-tool store --label=clonedev gitea api_token`
# NOTE: Gitea API Token needs the following permissions:
# read:organization
# read:repository
# read:user

list() {
	curl -s -X "GET" \
		"$API_URL/$1/$2/$ENDPOINT" \
		-H "accept: application/json" \
		-H "Authorization: token $TOKEN" |
		jq -r "$FILTER"
}

for target in $TARGETS; do
	type=$(echo "$target" | cut -d ':' -f 1)
	name=$(echo "$target" | cut -d ':' -f 2)
	for repo in $(list "$type" "$name"); do
		# shellcheck disable=2086
		echo $COMMAND "$repo"
	done
done