#!/usr/bin/bash
#
# Create a new repo.

umask 0002

# Figure out the environment we're running in
eval "$(crudini --format=sh --get /etc/dist-git/dist-git.conf dist-git)"
REPODIR=$gitroot_dir
DEFAULT_BRANCH=$default_branch
: ${git_author_name="Undefined"}
: ${git_author_email="undefined@example.com"}

if [ ! -d $REPODIR ] ; then
    echo "ERROR: This script has to be run on the git server."
    echo "ERROR: Homer sez 'Duh'."
    exit -9
fi

# Local variables
VERBOSE=0

Usage() {
    cat <<EOF
Usage:
    $0 <package_name>

    Creates a new repo for <package_name>

Options:
    -h,--help           This help message
EOF
}

while [[ $# > 0 ]]
do
key="$1"
case $key in
    --help|-h)
    Usage
    exit 0
    ;;
    *)
    PACKAGE="$1"
    ;;
esac
shift
done

# check the arguments
if [ -z "$PACKAGE" ] ; then
    Usage
    exit -1
fi

# optionally prepend default namespace if $PACKAGE is not namespaced
PACKAGE=`echo $PACKAGE | sed -e "s+^/*\([^/]*\)/*$+\1+"`
parts=($(echo $PACKAGE | tr "/" " "))
parts_len=${#parts[@]}
if [ -n "$default_namespace" ] && [ $parts_len -le 1 ]; then
    PACKAGE=$default_namespace/$PACKAGE
fi

# Sanity checks before we start doing damage
[ $VERBOSE -gt 1 ] && echo "Checking package $PACKAGE..."
if [ -f $REPODIR/$PACKAGE.git/refs/heads/$DEFAULT_BRANCH ] ; then
    echo "ERROR: Package module $PACKAGE already exists!" >&2
    exit 128
fi

# "global" permissions check
if [ ! -w $REPODIR ] ; then
    echo "ERROR: You can not write to $REPODIR"
    echo "ERROR: You can not create repos"
    exit -1
fi

# Now start working on creating those branches
# Create a tmpdir to do some git work in
TMPDIR=$(mktemp -d /tmp/tmpXXXXXX)

# First create the master repo
mkdir -p $REPODIR/$PACKAGE.git
pushd $REPODIR/$PACKAGE.git >/dev/null
git init -q --shared --bare
popd >/dev/null

mkdir -p $REPODIR/$PACKAGE.git/hooks/post-receive-chained.d
if [[ $grok && $grok != "False" ]]; then
    if ! [ -f $REPODIR/manifest.js.gz ]; then
        echo 'Generating initial grok manifest...'
        /usr/bin/grok-manifest -m $REPODIR/manifest.js.gz -t $REPODIR
    fi
    ln -s /usr/share/dist-git/hooks/grok_update \
        $REPODIR/$PACKAGE.git/hooks/post-receive-chained.d/grok_update
fi
# This one kicks off all the others in post-receive-chained.d
ln -s /usr/share/dist-git/hooks/post-receive \
    $REPODIR/$PACKAGE.git/hooks/post-receive

# Now clone that repo and create the .gitignore and sources file
git init -q $TMPDIR/$PACKAGE
pushd $TMPDIR/$PACKAGE >/dev/null
touch .gitignore
git config user.name "$git_author_name"
git config user.email "$git_author_email"
git add .
git commit -q -m 'Initial setup of the repo'
git remote add origin $REPODIR/$PACKAGE.git
git push -q origin "$DEFAULT_BRANCH"
popd >/dev/null

# Place the gitolite update hook in place since we're not using our own
if [[ $gitolite && $gitolite != "False" ]]; then
    ln -s /etc/gitolite/hooks/common/update $REPODIR/$PACKAGE.git/hooks/update
fi

rm -rf $TMPDIR
echo "Done."
