#!/usr/bin/env bash

# Copyright (C) 2014-2019 Maciej Delmanowski <drybjed@gmail.com>
# Copyright (C) 2015-2019 DebOps <https://debops.org/>
# SPDX-License-Identifier: GPL-3.0-only

# 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

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

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

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

  if [ -r "${worktree}/.git" ] ; then
    cd "${worktree}" || exit 1
    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

  # shellcheck disable=SC2034
  while read -r 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
