#!/usr/bin/env bash
#
# Split last $REV_LIMIT commits to separated dirs

. /etc/gitsplit/gitsplit.conf

cd $RULES_GIT_PATH
commits=`git log -n $REV_LIMIT --pretty=format:%H`
cd $RULES_PATH

(
flock -x 200 || exit 1

for commit in $commits; do
    commit_path="$RULES_PATH/$commit"
    if [ -d $commit_path ]; then
        echo "Version $commit_path already exist"
        continue
    fi

    tmp_path="$RULES_PATH/.$commit"
    if [ -d $tmp_path ]; then
        echo "Remove $tmp_path"
        rm -rf $tmp_path
    fi

    mkdir -p $tmp_path
    echo "Checkout $commit --> $tmp_path"
    git clone $RULES_GIT_PATH $tmp_path
    cd $tmp_path
    unset GIT_DIR
    git checkout -b version-$commit $commit
    echo "Submodule init"
    git submodule init
    echo "Submodule update"
    git submodule update
    cd $RULES_PATH
    mv $tmp_path $commit_path
done

# Clean up
if [ `ls | wc -l` -gt $REV_LIMIT ]; then
    echo "Cleanup..."
    (ls -t|head -n $REV_LIMIT;ls)|sort|uniq -u|xargs rm -r
fi
) 200>/run/lock/post-recive-hook.lock
