#!/bin/sh

###########################################################
# Script to import several CVS modules as subdirectories
# into a git repository. If necessary create the repository
# with git init, and perform a an initial commit committing
# something before running this script. git seems reluctant
# to merge into a completely empty repository.
# 
# Thanks to all the people who have placed useful git
# documentation on the web before me.

if [ -d .git ]
then
    # We are in a git repo, note the working directory.
    REPO_DIR=$(pwd)
else
    echo "No Git repo detected, please run in root of repo working tree."
    exit 1
fi;

# Loop through command line arguments, each should be a CVS module
for CVS_MODULE in $@
do
    
    # Put the module in an environment variable so git filter-branch sees it
    export __MODULE_AND_SUBDIR=$CVS_MODULE
    
    # Make a temporary repo for the operation
    mkdir /tmp/git_cvsmod2subdir_$__MODULE_AND_SUBDIR
    cd /tmp/git_cvsmod2subdir_$__MODULE_AND_SUBDIR
    
    # Perform CVS module import to repo, straight to the master branch
    # NOTE: Modify the CVS repository location to match your setup.
    nice git cvsimport -o master -v -d /var/cvs $__MODULE_AND_SUBDIR
    
    # Rewrite history and put the module in a subdir named after the module
    nice git filter-branch -f --index-filter \
            'git ls-files -s | sed "s-\t-&$__MODULE_AND_SUBDIR/-" |
             GIT_INDEX_FILE=$GIT_INDEX_FILE.new \
             git update-index --index-info &&
             if [ -f $GIT_INDEX_FILE.new ] ; then mv $GIT_INDEX_FILE.new $GIT_INDEX_FILE ; fi' HEAD
    
    # Go to original repo, fetch imported CVS module as a branch, and merge
    cd $REPO_DIR
    nice git fetch /tmp/git_cvsmod2subdir_$__MODULE_AND_SUBDIR master:cvsmodule-$__MODULE_AND_SUBDIR
    nice git merge cvsmodule-$__MODULE_AND_SUBDIR
    
    # Clean up the temporary repo
    rm -rf /tmp/git_cvsmod2subdir_$__MODULE_AND_SUBDIR
    
done

