#!/bin/bash

# Check out git branch to work directory

unset GIT_INDEX_FILE

real_bare="$(git config --get core.bare)"
bare="$(git config --get deploy.bare)"
worktree="$(git config deploy.worktree)"
branch="$(git config deploy.branch)"

set -e

export GIT_DIR="$(pwd)"
export GIT_WORK_TREE="${worktree}"

if [ -n "${bare}" -a "${bare}" = "false" ] ; then

  test -d ${worktree} || mkdir -p ${worktree}

  if [ -r ${worktree}/.git ] ; then
    cd ${worktree}
    if ! $(git diff --quiet) ; then
      echo "Error: Found tracked changes in work directory, aborting" && exit 1
    fi
    if $(git ls-files --others --exclude-standard | grep >/dev/null .) ; then
      echo "Error: Found untracked files in work directory, aborting" && exit 1
    fi
    cd - > /dev/null
  fi

  while read oldrev newrev ref ; do

    if [ -z "${branch}" ] ; then
      branch="${ref##refs/heads/}"
      git symbolic-ref HEAD ${ref}
      git config deploy.branch ${branch}
      git config deploy.ref ${ref}
    fi
    if [[ ${ref} =~ .*/${branch}$ ]] ; then
      echo "gitdir: ${GIT_DIR}" > ${worktree}/.git
      git config deploy.bare false
      git config core.bare false
      git config core.worktree ${worktree}
      git config receive.denyCurrentBranch ignore
      if [ "${real_bare}" = "${bare}" ] ; then
        git checkout -f ${branch}
      else
        git checkout -f
      fi
    fi

  done
fi

