Files
ops/backups/scripts/gitea-mirror-export.sh

61 lines
1.4 KiB
Bash

#!/usr/bin/env bash
set -Eeuo pipefail
trap 'echo "Error on line $LINENO during mirror export" >&2' ERR
ensure_writable_dir() {
local dir="$1"
mkdir -p "$dir"
if [[ ! -d "$dir" || ! -w "$dir" ]]; then
echo "Output directory is not writable: $dir" >&2
exit 1
fi
}
GITEA_URL="${GITEA_URL:-https://git.sketchferret.com}"
TOKEN_FILE="${TOKEN_FILE:-/srv/secrets/gitea_token}"
OUT="${OUT:-/srv/backups/git-mirrors}"
OWNER="${OWNER:-spencer}"
if [[ ! -f "$TOKEN_FILE" ]]; then
echo "Missing token file: $TOKEN_FILE"
exit 1
fi
TOKEN="$(cat "$TOKEN_FILE")"
ensure_writable_dir "$OUT/$OWNER"
repos_json="$(curl -fsSL -H "Authorization: token $TOKEN" "$GITEA_URL/api/v1/users/$OWNER/repos?limit=1000")"
mapfile -t urls < <(python3 - <<'PY' "$repos_json"
import json,sys
for repo in json.loads(sys.argv[1]):
print(repo["clone_url"])
PY
)
if [[ "${#urls[@]}" -eq 0 ]]; then
echo "No repositories returned for owner '$OWNER' from $GITEA_URL" >&2
exit 1
fi
for url in "${urls[@]}"; do
name="$(basename "$url" .git)"
target="$OUT/$OWNER/$name.git"
auth_url="$url"
if [[ "$url" == https://* ]]; then
auth_url="https://${TOKEN}:x-oauth-basic@${url#https://}"
fi
if [[ -d "$target" ]]; then
git -C "$target" remote set-url origin "$auth_url"
git -C "$target" fetch --prune
else
git clone --mirror "$auth_url" "$target"
fi
done
echo "Mirror export complete: $OUT/$OWNER"