#!/bin/sh

set -eu

#######################################
# transfer repository owner
# Globals:
#   GH_TOKEN
# Arguments:
#   1   repository name
#   2   previous owner
#   3   new owner
#######################################
main() {
  case "$1" in
    -h|--help|help) printf "%s\n"  "usage: ${0##*/} <repo> <owner> <new_owner>" "" "transfer repository owner"; exit ;;
  esac

  tmp="$(mktemp)"
  url="https://api.github.com/repos/$2/$1/transfer"
  curl -s \
    -X POST  \
    -H "Accept: application/vnd.github.v3+json" \
    -H "Authorization: token ${GH_TOKEN}" \
    "${url}" \
    -d "{\"new_owner\":\"$3\"}" > "${tmp}"
    if grep -q \"message\": "${tmp}"; then
      echo "${url}"
      jq . "${tmp}"
      exit 1
    fi
}

main "$@"
