summaryrefslogtreecommitdiff
path: root/modules/nixos/custom/github-mirror/update-mirror.sh
blob: 88ff6eb88885ae60fd5e925723f6728ca1927180 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/usr/bin/env bash
set -euo pipefail

help() {
	echo "Mirror a GitHub user's repositories

Usage: $(basename "$0") [options] <user>...

Options:
  -h --help                         Show this screen
  -d --directory DIRECTORY          Where to clone repositories (defaults to ./git)"
}

create_if_not_exists() {
	if [ ! -d "$1" ]; then
		mkdir -p "$1"
	fi
}

repo_endpoint() {
	echo "https://api.github.com/users/$1/repos"
}

users=()
output_directory="git"

while [ "$#" -gt 0 ]; do
	case $1 in
	-h | --help)
		help
		exit 0
		;;
	-d | --directory)
		output_directory="$2"
		shift
		shift
		;;
	-*)
		echo "error: unknown option $1"
		help
		exit 1
		;;
	*)
		users+=("$1")
		shift
		;;
	esac
done

if [ "${#users[@]}" -lt 1 ]; then
	echo "error: at least one user must be specified"
	help
	exit 1
fi

create_if_not_exists "$output_directory"
cd "$output_directory"

for user in "${users[@]}"; do
	create_if_not_exists "$user"

	url="$(repo_endpoint "$user")"
	curl --fail --location --show-error --silent "$url" | jq --raw-output '.[].name' | while read -r repo; do
		repo_path="$user"/"$repo"

		if [ -d "$repo_path" ]; then
			pushd "$repo_path" &>/dev/null
			echo "Pulling $repo_path..."
			if ! git remote update --prune &>/dev/null; then
				echo "Unable to pull $repo_path! Continuing..."
			fi
			popd &>/dev/null
		else
			echo "Cloning $repo_path..."
			git clone --bare --mirror https://github.com/"$repo_path".git "$repo_path" &>/dev/null
		fi
	done
done