#!/bin/sh
#
# Copyright (c) 2026 Jacob Edwards <jacob@jacobedwards.org>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIE
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

set -eu

log() {
	echo "$(basename "$0"): $@" 1>&2
}

err() {
	log "$@"
	exit 1
}

update() {
	export GIT_DIR="$d"

	case $(git rev-parse --is-bare-repository) in
	(true) ;;
	(false)
		log "$GIT_DIR: Isn't a bare git repository"
		return 1
	esac

	name="$(basename "$(git rev-parse --absolute-git-dir)" | sed 's/\.git$//')"
	path="$user/$name"

	visibility=private
	test -f "$GIT_DIR/${pubfile:-git-daemon-export-ok}" &&
		visibility=public

	if ! gh repo view "$path" >/dev/null 2>&1
	then
		log "Creating github.com/$path"
		gh repo create "$path" --$visibility >/dev/null
	fi

	test -f "$GIT_DIR"/homepage &&
		homepage="$(cat "$GIT_DIR"/homepage)"

	log "Updating github.com/$path"
	gh repo edit "$path" \
		${homepage:+-h "$homepage"} \
		-d "$(cat "$GIT_DIR"/description)" \
		--visibility "$visibility" \
		--accept-visibility-change-consequences >/dev/null

	archived=false
	test -f "$GIT_DIR/${archivefile:-archived}" &&
		archived=true

	! $archived &&
	    gh repo unarchive "$path" -y

	log "Pushing to github.com/$path"
	git push --mirror "git@github.com:$user/$name"

	if $archived; then
		log "Archiving github.com/$path"
		gh repo archive "$path" -y
	fi
}

while test $# -gt 0
do
	case "$1" in
	(-a) archivefile="${2:?-a: requires an argument}"; shift ;;
	(-p) pubfile="${2:?-p: requires an argument}"; shift ;;
	(-t) export GH_TOKEN="${2:?-t: requires an argument}"; shift ;;
	(--) shift; break ;;
	(-*) err "$1: Invalid option
usage: github-mirror [-a archivefile] [-p pubfile] [-t pat] [repo ...]" ;;
	(*) break ;;
	esac
	shift
done

printenv GH_TOKEN >/dev/null ||
	err "GH_TOKEN is unset and -t wasn't passed"

user="$(gh api user --jq .login)"
test $# -eq 0 &&
	set -- "${GIT_DIR:-.}"

for d in "$@"
do
	update "$d" ||
	    status=1
done

exit ${status:-0}
