#!/usr/bin/env bash

# Run deployment script

oldrev="${1}"
newrev="${2}"

system_functions="$(git config --global --get gitusers.system.functions)"
# shellcheck disable=SC1090
test -x "${system_functions}" && source "${system_functions}"

read -r -a permissions <<< "$(git config --global --get gitusers.permissions)"
worktree="$(git config --get deploy.worktree)"
public="$(git config --get deploy.public)"
setup="$(git config --get deploy.setup)"

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

cd "${worktree}" || exit 1

if [ -n "${public}" ] ; then
  export DEPLOY_PUBLIC="${public}"
fi

logfile="log/deploy.log"
restartfile="tmp/restart.txt"

if [ -n "${permissions[*]}" ] && in_array permissions deploy ; then

  if [ -z "${setup}" ]; then

    # this is the first push; this branch was just created
    mkdir -p log tmp
    chmod 0775 log tmp
    touch $logfile $restartfile
    chmod 0664 $logfile $restartfile

    # execute the one-time setup hook
    if [ -x deploy/setup ] ; then
      echo "DEPLOY_PUBLIC=\"${DEPLOY_PUBLIC}\""
      deploy/setup "${oldrev}" "${newrev}" 2>&1 | tee -a "${logfile}"
    fi
    git config deploy.setup true

  else

    mkdir -p log tmp
    chmod 0775 log tmp
    touch $logfile $restartfile
    chmod 0664 $logfile $restartfile

    # log timestamp
    echo "==== $(date) ====" >> "${logfile}"

    # execute the main deploy hook
    if [ -x deploy/after_push ] ; then
      echo "DEPLOY_PUBLIC=\"${DEPLOY_PUBLIC}\""
      deploy/after_push "${oldrev}" "${newrev}" 2>&1 | tee -a "${logfile}"
    fi

  fi

else

  if test -x "${worktree}/deploy/setup" ; then
    echo "No permission to run deploy script"
  fi

fi
