#!/bin/sh
#
# This script checks out a specific version of the kernel as stored in
# the .versions file.  Usage is simple, make sure your $CVSROOT is set and:
#   version-checkout CVS-module kernel-version
# for example:
#   version-checkout linux-2.6 2.6.8.1-pa1
#
# WARNING WARNING WARNING this script will RUIN your ./CVS-module, in the
# example ./linux-2.6 WARNING WARNING WARNING
#
# Coaxing CVS to reproduce a nice tree from a list of files and their
# versions turns out to be remarkably difficult to do with any speed
# due to various curious problems with CVS :-(
#

pause() {
    echo -n "$@" pausing...\ 
    read a
}

if [ $# != 2 ]
then
    echo "Usage: $0 cvs-module(e.g. linux-2.6) kernel-ver(e.g., 2.6.0-pa1)" >&2
    exit 2
fi

MODULE=$1
VER=$2

# save a copy of the versions file
TMP=/tmp/vco$$.$RANDOM
VFILE=$TMP-vf
trap "rm -f $TMP-*" 0 1 2 3 15

cvs co $MODULE/.versions

VERVER=$(
	cvs log $MODULE/.versions |
	awk -v ver=$VER '
		(NF == 2 && $1 == "revision") { lastrev = $2; next }
		(NF == 1 && $1 == ver) { if (verver == "") verver = lastrev }
		END { print verver }
		'
	)

[ -z "$VERVER" ] &&
    echo "ERROR: Could not find .versions record for kernel version $VER" >&2

# pause "Kernel version $VER is .versions version $VERVER"

cvs co -p -r$VERVER $MODULE/.versions > $VFILE

# pause vfile in $VFILE

rm -rf $MODULE

# CVS is remarkably bad about creating needed directories with 'cvs update'
# and much better with 'cvs co' -- sad but true...

sed -e 's:/[^/]*$::' -e 's:^\./::' < $VFILE | sort -u > $TMP-dirlist

cvsmkdir() {
    c=$2$3/CVS
    # echo cvsmkdir $c
    echo -n .
    # root module subdir
    mkdir -p $c
    echo $2$3 > $c/Repository
    echo $1 > $c/Root
    echo -n > $c/Entries
}

# pause $TMP-dirlist

cvsmkdir $CVSROOT $MODULE ""
while read dirname
do
    [ $dirname = . ] && continue
    cvsmkdir $CVSROOT $MODULE /$dirname
done < $TMP-dirlist

# pause dirs created

# cvs up is much faster than cvs co and we can us it now that dirs are made
cd $MODULE

vlist=$(cut -f2 "$VFILE" | sort -u)
# pause $vlist

for v in $vlist
do
    echo -n $v...
    awk -vv=X$v '("X" $2 == v && $1 != "./.versions") {print $1}' < $VFILE |
        xargs --no-run-if-empty cvs -Q up -r$v
    echo
done
