#!/bin/bash
set -xe

APP="$1"
VERSION="$2"
PRIOR="$3"
APPLICATION="$4"

if [ -z "$APPLICATION" ]; then
    echo "$0 APP VERSION PRIOR-VERSION APPLICATION"
    echo
    echo "Prepares a retroactive upgrade on a repository.  Be"
    echo "sure to run tests/prepare-upgrade.sh on the resulting"
    echo "commits on a scripts server."
    echo
    echo "      APP : short name, like 'wordpress'"
    echo "      VERSION : version being retro'd"
    echo "      PRIOR-VERSION : version to retro on to"
    echo "      APPLICATION : full name of application for commit message"
    echo
    echo "See docs/upgrade.rst <http://scripts.mit.edu/wizard/upgrade.html>"
    echo "for detailed instructions."
    exit 1
fi

git checkout -b tmaster || git checkout tmaster
git reset --hard $APP-$PRIOR-scripts
git checkout -b tpristine || git checkout tpristine
git reset --hard $APP-$PRIOR

DATE=`git show tmaster --pretty="format:%cd" | head -n1`

export GIT_AUTHOR_DATE="$DATE"
export GIT_COMMITTER_DATE="$DATE"

wizard prepare-pristine $APP-$VERSION --force
git commit -asm "$APPLICATION $VERSION"
git tag $APP-$VERSION

git checkout tmaster
git merge tpristine --no-commit || (echo "Dropping into shell; exit when complete." && bash) || true
git commit -asm "$APPLICATION $VERSION-scripts"
git tag $APP-$VERSION-scripts
