#!/bin/sh
# Copyright (c) 2007 David Soria Parra <dsp at php dot net>
#
# Licensed under the terms of the MIT License
# See /usr/share/doc/gcutils/copyright
# or http://www.opensource.org/licenses/mit-license.php

. /opt/local/lib/gc-sh-setup

usage ()
{
    echo "Usage:" `basename $0` "[OPTIONS] <cvsroot> <module>"
    echo "Options are:"
    echo "    -h            show help"
    echo "    -v            verbosity"
    echo "    -d <dir>      directory for checkout"
    echo "    -gu           convert underscores during gitimport"
    echo "    -gn           pass --no-cvs-direct to cvsps"
    echo "    -u            do not write an ignore file"
    echo "    -V            show version information"
    echo "    -r <remote>   used refs/remotes/<remote>/ to import CVS branches into"
    echo "                  default is 'cvs'"
    echo
    exit 127
}

check_git

verbose=
cvrtudsr=
dir=
quiet="-Q"
ignorefile="t"
remote="cvs"
opts=
while test $# != 0
do
    case "$1" in
        -u)
            ignorefile=
            ;;
        -v)
            verbose="-v"
            quiet=
            ;;
        -r)
            shift
            remote="$1"
            ;;
        -d)
            shift
            dir="$1"
            ;;
        -gu)
            cvrtudsr="-u"
            ;;
        -gn)
            opts="-p '--no-cvs-direct'"
            ;;
        -h)
            usage
            ;;
        -V)
            version
            exit
            ;;
        -*)
            echo >&2 "Parameter $1 is not known."
            usage
            ;;
        *)
            break
            ;;
    esac
    shift
done

CVSROOT=$1
MODULE=$2

test $# != 2 && usage

echo "Repository: $CVSROOT"
echo "Module:     $MODULE"
echo

test ${#dir} -eq 0 && dir="$MODULE"

if test -d "$dir/.cvs"
then
    echo >&2 "It seems that you are trying to use gc-import on an allready tracked repository."
    die "Please use gc-update instead"
fi

test -d "$dir" && die "directory $dir exists"

mkdir $dir

git cvsimport $opts -r "$remote" -a -k $verbose $cvrtudsr -m -d$CVSROOT -C "$dir" $MODULE && cd "$dir" && git config gc-utils.remote "$remote" && echo "Initialize CVS repository in $PWD/.cvs" && cvs -d$CVSROOT $quiet -z 9 co -d ".cvs" $MODULE

test $? != 0 && die "Failed."

if test -n "$ignorefile"
then
    if test ! -f ".gitignore"
    then
        echo ".cvs" > ".gitignore" && echo "Create ignore file in $PWD/.gitignore"
    else
        echo ".cvs" >> ".gitignore" && echo "Add ignore entry to $PWD/.gitignore"
    fi
fi
