#!/bin/bash

. ${TOOLKIT}-functions.sh

set -e

# git home is defined by giy.repofi (formerly path.gitdir) entry,
# here we check if the actual git user needs to be updated
#
git_home=$(jtconf git.repodir)

user="git"
group=$(getent passwd git | cut -d':' -f 4)
home=$(getent passwd git | cut -d':' -f 6)

if [ "X$git_home" != "X$home" ]
then
	putwarning "GIT HOME CHANGED" \
	  "updating 'git' user; please make sure to manually move" \
	  "the home dir from '$home' to new location '$git_home'"
	usermod --home "$git_home" git
else
	jtmkpath -v $home $user:$group 700

	[ -d $home/.gitolite ] || {
    	putwarning "GITOLITE SETUP" \
	  "to finish git (gitolite) setup you need:\n\n" \
	  "  . a file containing the admin pub ssh key (eg: admin.pub)\n" \
	  "  . run the setup command\n\n" \
	  "su - $user -c \"gitolite setup -pk admin.pub\""
	}
fi


# fix broken hooks
#
cd "$home"
for hook in $( ls \
	repositories/*/hooks/update \
	repositories/gitolite-admin.git/hooks/post-update \
	2>/dev/null || :) 
do
	[ -e "$hook" ] || {
		echo "  repair broken hook: $hook"
		dir=$(dirname "$hook")
		file=$(basename "$hook")
		cd "$dir"
		case $file in
		  update)	subdir="common" ;;
		  post-update)	subdir="gitolite-admin" ;;
		esac
		rm -f $file
		ln -s "../../../.gitolite/hooks/$subdir/$file" .
		cd "$home"
	}
done

for dir in $(ls -d repositories/*/hooks 2>/dev/null || :)
do
	symlinks -c "$dir"
done

exit 0
