#!/bin/bash
local PROJECT_NAME=$1
local PROJECT_PATH=/home/git/$PROJECT_NAME
local PROJECT_REPO=/home/git/$PROJECT_NAME.git
local USEREXISTS_GIT=$(userExists git)

shift
local ON_RECEIVE=$(echo $@ | tr '\237' '\n')

# if we don't have custom ON_RECEIVE logic, use the default update
# handling from dominic's deploy example
if [ ! "$ON_RECEIVE" ]; then
  read -d '' ON_RECEIVE <<SCRIPT
if [ -e update ]; then 
  ./update
fi
SCRIPT
fi

function postReceive {
  cat <<SCRIPT
#!/bin/bash

# post-receive hook
# adapted lightly from: https://github.com/dominictarr/deploy

while read -a line; do
  branch=\${line[2]##refs/*/}
  work_tree="$PROJECT_PATH/\$branch"
  git_dir="\$PWD"
  mkdir -p "\$work_tree"; pushd "\$work_tree"
  git --work-tree "\$work_tree" --git-dir "\$git_dir" checkout "\$branch" --force
  $ON_RECEIVE
  popd
done  
SCRIPT
}

# we need write access to home to be able to make this work
[[ -w /home ]] || abort "Need to be able to create users to enable gitserver"

# if no project has been specified, then abort
[[ $PROJECT_NAME ]] || abort "No project name specified, install using githost name"

hash git 2> /dev/null || require packages git

# don't run the install process if we are in use mode
if [ ! $USEREXISTS_GIT ]; then
  # if we don't have the latest node version, then install
  log "creating the git user"
  rm -rf /home/git
  useradd -s /usr/bin/git-shell -m -d /home/git git

  # make our .ssh directory
  mkdir -p /home/git/.ssh
fi

# ensure we have a projects directory
if [ ! -d /home/git/$PROJECT_NAME ]; then
  log "- creating git project folder: $PROJECT_NAME"
  sudo -u git mkdir -p $PROJECT_PATH $PROJECT_REPO
  sudo -u git git init --bare $PROJECT_REPO

  log "- initializing post receive hook"
  postReceive > $PROJECT_REPO/hooks/post-receive
  chown git:git $PROJECT_REPO/hooks/post-receive
  sudo -u git chmod a+x $PROJECT_REPO/hooks/post-receive
fi