#!/bin/sh
set -eux

# Fetch before the split.
#
# If a `git-subtree-split:` line refers to a commit that we don't have
# locally (because it has been garbage collected, because
# build-aux.git isn't a remote in .git/config), then `git subtree`
# will do the wrong thing (instead of just aborting, because crappy
# error handling), and potentially push proprietary code to
# build-aux.git.  So do a fetch first, to guarantee that build-aux
# commits exist locally.
git fetch https://github.com/datawire/build-aux.git

# Split.
origin=$(git remote get-url origin)
name=$(printf '%s\n' "$origin" | sed -e 's,\.git/*$,,' -e 's,.*/,,')
commit=$(git subtree split --annotate="(${name}) " --prefix=build-aux HEAD)

# Push the split.
git push git@github.com:datawire/build-aux.git "${commit}:master"

# Rejoin after the split.
#
# If project A does a `build-aux-push` to push some commits to
# build-aux.git, then some other commits go on build-aux.git that touch
# the same parts of the same files, then project A's next
# `build-aux-pull` will result in merge conflicts!  Even though it
# should be a fast-forward merge!
#
# This is because git doesn't have the full history to now that it's a
# ff; it lost some intermediate state.
#
# `git subtree split` has a `--rejoin` flag that's designed to fix
# exactly this:
#
#      --rejoin
#            This option is only valid for the split command.
#
#            After splitting, merge the newly created synthetic history
#            back into your main project. That way, future splits can
#            search only the part of history that has been added since
#            the most recent --rejoin.
#
#            If your split commits end up merged into the upstream
#            subproject, and then you want to get the latest upstream
#            version, this will allow git’s merge algorithm to more
#            intelligently avoid conflicts (since it knows these
#            synthetic commits are already part of the upstream
#            repository).
#
# Yay!  Except it goes on to say:
#
#            If you do all your merges with --squash, don’t use --rejoin
#            when you split, because you don’t want the subproject’s
#            history to be part of your project anyway.
#
# Boo!  We do use `--squash`.  The flag isn't quite smart enough to
# automatically do a new `--squash`, so we have to do it ourselves.
# Fortunately, we already have a `build-aux-pull` script that does
# exactly this.
"${0%-push}-pull" "$commit"
