#!/bin/bash
#
# Configuration
# -------------
# hooks.deployDir
#   The directory where your non-bare repo lives that should be deployed to
# hooks.deployBranch
#   Deploy this branch
# hooks.deployPost
#   Command to run after the deploy, e.g. to restart a webserver or minify files

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

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

deploydir=$(git config hooks.deploydir)
deploybranch=$(git config hooks.deploybranch)
deploypost=$(git config hooks.deploypost)
test -z "$deploydir" && die "hooks.deploydir 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
        echo "Deploying $deploybranch@${newrev:0:8} to $deploydir"
        (
            unset GIT_DIR
            cd "$deploydir"
            if [ -n "$(git status -s 2>&1)" ]; then
                die "working directory dirty"
            fi
            git fetch
            git reset --hard "origin/$deploybranch"
            if [ -n "$deploypost" ]; then
                sh -c "$deploypost"
            fi
        )
    fi
done
