#!/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] <sha1>"
    echo "Options are:"
    echo "    -h        show help"
    echo "    -C        run a cvsclean. "
    echo "              WARNING: this will run cvs up -C"
    echo "              and then remove all found .#* files"
    echo "    -c        commit to cvs if no errors occured"
    echo "    -f        force patching in case of an unclean"
    echo "              cvs repository"
    echo "    -V        show version information"
    echo
    exit 127
}

check_git

cvsclean=
commit=
force=
while test $# != 0
do
    case "$1" in
        -c)
            commit="-c"
            ;;
        -C)
            cvsclean=t
            ;;
        -f)
            force="-f"
            ;;
        -h)
            usage
            ;;
        -V)
            version
            exit
            ;;
        -*)
            echo >&2 "Parameter $1 is not known."
            usage
            ;;
        *)
            break
            ;;
    esac
    shift
done

test $# = 0 && usage

locate_git_repo

if test ! ".cvs" -o ! -d ".cvs/CVS/"
then
    echo >&2 "CVS working directory not found."
    die "Make sure you imported your CVS repository using gc-import."
fi

test "$cvsclean" = "t" && cd ".cvs" && cvs up -C && find . -iname ".#*" -exec rm '{}'

if test -d ".git" -a -d ".cvs"
then
    cd ".cvs"
    GIT_DIR="../.git" git cvsexportcommit -v $force $commit -u $1
else
    test ! -d ".git" && die "Not a git repository"

    if test ! -d ".cvs"
    then
        echo >&2 "No cvs repository found in .cvs. "
        die "Make sure you follow the standards"
    fi
fi
