#!/bin/bash
#
# Configuration
# -------------
# hooks.deployDir
#   The directory where your deployments live
# hooks.deployLink
#   The symlink in that directory that points to the current deploy
# hooks.deployBranch
#   Deploy this branch
# hooks.deployPost
#   Command to run after the deploy, but before the deploy is activated
# hooks.deployActivate
#   Command to run after the deploy has been activated

die() {
    echo >&2 "fatal: post-receive-deploy: $1"
    exit 1
}

test -z "$GIT_DIR" && die "GIT_DIR not set"

deploydir=$(git config hooks.deploydir)
deploylink=$(git config hooks.deploylink)
deploybranch=$(git config hooks.deploybranch)
deploypost=$(git config hooks.deploypost)
deployactivate=$(git config hooks.deployactivate)
test -z "$deploydir" && die "hooks.deploydir not set"
test -z "$deploylink" && die "hooks.deploylink not set"
test -d "$deploydir" || die "deploy directory $deploydir does not exist"
test -z "$deploybranch" && die "hooks.deploybranch not set"

while read oldrev newrev refname; do
    if [ "$refname" = "refs/heads/$deploybranch" ]; then
        deploy="$deploybranch@${newrev:0:8}"
        echo "Deploying $deploy to $deploydir/$deploy"
        if [ -e "$deploydir/$deploy" ]; then
            # This happens when re-pushing a tip that has been tip before
            echo "$deploydir/$deploy exists, skipping"
            exit 0
        fi

        git archive --prefix="$deploy/" $newrev | tar -C "$deploydir" -x

        if [ -n "$deploypost" ]; then
            ( cd "$deploydir/$deploy" && sh -c "$deploypost" )
        fi

        echo "Activating $deploydir/$deploy as $deploydir/$deploylink"
        ln -sf -T "$deploy" "$deploydir/$deploylink"
        if [ -n "$deployactivate" ]; then
            ( cd "$deploydir/$deploylink" && sh -c "$deployactivate" )
        fi
    fi
done
