#!/bin/sh -e

#
# check out the Makefile implied by MODULE.  If the current kernel
# version is not represented by a CVS tag, set the tag and optionally
# create a .versions file
#
# exit code 2 means no work performed, 0 means tag emplaced
#

#-----------------------------------------------#
CVSROOT=${CVSROOT:-/var/cvs}

MODULE=linux
VERSIONS=true

while [ $# != 0 ]
do
    case $1 in
        -m) MODULE=$2; shift 2;;
	-d) CVSROOT=$2; shift 2;;
	-noversions) VERSIONS=false; shift 1;;
	*) echo "Usage: $0 [-m module] [-d CVSROOT] [-noversions] [-exec foo]" >&2
	   echo "If you want a version list file, create .versions in CVS in" >&2
	   echo "the top level and make sure 'cvs-versions' is in the \$PATH" >&2
	   echo "when you run this." >&2
	   exit 2;;
    esac
done

#-----------------------------------------------#

TMPDIR=/tmp/$(basename $0)-$$-$RANDOM
# trap "rm -fr $TMPDIR" 0 1 2 3 15

CVS() {
    cvs -Qfz4 -d$CVSROOT "$@"
}

# print the tag list associated with cvs file $1
show_tags() {
    CVS log $1 |
    awk '
	(/symbolic names:$/) {
	    state = 1
	    next
	}
	(state == 1 && !(/^[ 	]/)) {
	    state = 2
	}
	(state == 1) {
	    sub(":", "", $1)
	    print $1
	}'
}

# test if item $1 is in list $(2-n)
in_list() {
    typeset q=$1
    typeset item

    shift 1
    for item in $*
    do
        [ $item = $q ] && return 0
    done

    return 1
}

# in the top-level kernel directory, figure out the kernel version
# from the Makefile
linux_kernel_version() {
    head > /tmp/lkv$$
    echo -e '\nlkv:\n\t@echo $(VERSION).$(PATCHLEVEL).$(SUBLEVEL)$(EXTRAVERSION)' >> /tmp/lkv$$
    make -f /tmp/lkv$$ lkv
    rm -f /tmp/lkv$$

    # Really need a sanity check for the day when the makefile changes
}

info() {
    echo "info: $@" >&2
}

fixpath()
{
    # need to adjust $PATH to contain directory of this script, in which
    # other thins area assumed to live as well
    SCRIPTDIR=$(dirname $0)
    case X$SCRIPTDIR in
	X/) : ;;
	X.) SCRIPTDIR=$PWD ;;
	X.*) SCRIPTDIR=$PWD/$SCRIPTDIR ;;
    esac
    PATH=$SCRIPTDIR:$PATH
}

cleanup() {
    rm -fr $TMPDIR
}

info "\$Id: autotag-kernel-tree,v 1.1 2004/11/10 23:55:01 bame Exp $"

fixpath
STARTDIR=$PWD
mkdir -p $TMPDIR

mkdir -p $TMPDIR/cvs
cd $TMPDIR/cvs
CVS co -l $MODULE
cd $MODULE

show_tags Makefile | version-order | sort -r > $TMPDIR/tags
kernelver=$(linux_kernel_version < Makefile)
set -- $(echo $kernelver | version-order)
vo_kernelver=$1
vo_cvskernelver=$4

# no work to do if already tagged
if fgrep $vo_kernelver $TMPDIR/tags >/dev/null 2>&1
then
    cleanup
    exit 2
fi

echo CVS rtag -F $vo_cvskernelver $MODULE

if [ -f .versions -a $VERSIONS = true ]
then
    cvs-versions > .versions &&
	CVS commit -m"$kernelver" .versions
fi

cleanup
exit 0
