#!/bin/bash

echo 1>&2
echo "cvstripwire - tests for files in a checked out CVS module that have been" 1>&2
echo "              changed by someone else." 1>&2
echo "Copyright (c) Clarence Dang 2004" 1>&2
echo 1>&2


mode="$1"
if [ "$mode" != "setup" ] && [ "$mode" != "test" ]
then
    echo "Usage:" 1>&2
    echo "1. 'cvstripwire setup' creates .cvstripwire files with MD5s of checked out files" 1>&2
    echo "2. Then, you can safely type 'cvs update'" 1>&2
    echo "3. Finally, type 'cvstripwire test' to find out what files have been changed by" 1>&2
    echo "   others" 1>&2
    echo 1>&2
    # TODO: could fix this but would have to create a backup of all the files
    echo "WARNING: this reports most changes but not all - MD5s are NOT unique." 1>&2
    echo 1>&2
    
    exit 1
fi


for dir in `find -type d -name CVS`
do
    if ! pushd "$dir/.." >/dev/null
    then
        echo "Could not change to $dir/.. - very confused" 1>&2
        exit 1
    fi

    if [ "$mode" == "setup" ]
    then
        echo -n "S " 1>&2
    elif [ "$mode" == "test" ]
    then
        echo -n "T " 1>&2
    fi
    echo `echo "$dir" | sed -e 's/\/CVS$//'` 1>&2
    
    if [ ! -f "CVS/Entries" ]
    then
        echo "CVS/Entries doesn't exist." 1>&2
    else
        files="`egrep '^/[^/]+/' "CVS/Entries" | cut -d/ -f2`"
        if [ "$files" ]
        then
            md5sum $files > .cvstripwire-temp
            
            if [ "$mode" == "setup" ]
            then
                mv ".cvstripwire-temp" ".cvstripwire"
            elif [ "$mode" == "test" ]
            then
                if [ ! -f ".cvstripwire" ]
                then
                    echo ".cvstripwire doesn't exist." 1>&2
                else
                    diff -U0 ".cvstripwire-temp" ".cvstripwire"
                fi
            
                rm ".cvstripwire-temp"
            fi
        fi
    fi

    if ! popd >/dev/null
    then
        echo "Could not popd - very confused" 1>&2
    fi
done

