#!/bin/sh

set -eu

# Exit with an error if GIT_DIR isn't set
: ${GIT_DIR:?Expected GIT_DIR to be defined.}

# Load GitHub PAT token for gh
GH_TOKEN="$(cat ~/gh_token)"
export GH_TOKEN

# Get user & repository information
# for git push; gh defaults to the authenticated user
user="$(gh api user --jq .login)"
name="$(basename "${GIT_DIR%.git}")"
path="$user/$name"

# Set to public if git-daemon-export-ok exists
visibility=private
test -f "$GIT_DIR"/git-daemon-export-ok &&
	visibility=public

# Create/update repository on GitHub
echo gh repo create "$path" --"$visibility" ||
    true
echo gh repo edit "$path" \
    --visibility "$visibility" \
    -d "$(cat "$GIT_DIR"/description)" \
    --accept-visibility-change-consequences

# Push updates
git push --mirror git@github.com:"$path"
