#!/bin/bash
# Push the current dir's git repo, forcing the "origin" remote to SSH first.
#
# Some environment automatically rewrites origin back to an https:// URL
# (with an embedded access token) between sessions. Plain `git push` then
# fails or re-auths via that token, so this switches origin to the
# corresponding git@host:path.git SSH URL before pushing.
#
# Any arguments are passed straight through to `git push`.

set -uo pipefail

url="$(git remote get-url origin)" || exit 1

case "$url" in
    https://*)
        ssh_url="$(echo "$url" | sed -E 's#https://([^/]+)/(.+?)(\.git)?$#git@\1:\2.git#')"
        echo "Switching origin: $url -> $ssh_url"
        git remote set-url origin "$ssh_url" || exit 1
        ;;
    git@*)
        ;;
    *)
        echo "git-push: unrecognized origin URL '$url', leaving as-is" >&2
        ;;
esac

git push "$@"
