#!/bin/sh

CVSQ_VERSION="0.4.4"


help()
{
  echo "
cvsq $CVSQ_VERSION
by Vaclav Slavik, 2000-2004

Usage: cvsq <operation>
   where <operation> is
     --help or -h           displays this message
     --version or -v        displays version info
     upload                 proceeds all scheduled cvs commands
     (anything else)        passed to cvs. The command is stored in ~/.cvsq
                            and will be proceed when you run cvsq upload
                            Exception: commands update, checkout, log, login
                            are executed immediately
                            
Example 1:
   cvsq commit -m \"log message\" myfile.cpp
   cvsq upload

Example 2:
   cvsq project mahogany
   cvsq commit -m \"added message colorizing\" wxMessageView.cpp
   cvsq upload mahogany
  "
}

# -- colorizer initilization: ---
color_ltgreen="\033[1;32m"
color_ltred="\033[1;31m"
color_off="\033[0m"

echo_ok()
{
    echo -e "$color_ltgreen [ OK ] $color_off"
}


echo_failed()
{
    echo -e "$color_ltred [ FAILED ] $color_off"
    echo "  (leaving in the queue)"
}


output_cmd()
{
    echo "cd "`pwd`
    cmdlin=""
    while [ $# -gt 0 ] ; do
       cmdlin="$cmdlin \"$1\""
       shift
    done
    echo "$cmdlin"
    echo "exit \$?"
}

output_command()
{
    output_cmd "$@" >>$HOME/.cvsq/todo/$SLOT_NUM
}




first_free_slot()
{
    SLOT=`{ echo 0; ls $HOME/.cvsq/todo; } | sort -n | tail -n 1`
    SLOT=`expr $SLOT + 1`
    echo $SLOT
}



upload_changes()
{
    ls $HOME/.cvsq/todo | sort -n  | while read slot ; do
        if [ ! -f "$HOME/.cvsq/todo/$slot" ] ; then
            echo "Nothing in queue, exiting."
        else
            sh $HOME/.cvsq/todo/$slot
            if [ $? -eq 0 ] ; then
                echo_ok
                rm -f $HOME/.cvsq/todo/$slot 
            else
                echo_failed
            fi
        fi
    done
}




if [ $# -eq 0 ] ; then
    help
    exit    
fi


[ -d $HOME/.cvsq ] || mkdir $HOME/.cvsq
[ -d $HOME/.cvsq/todo ] || mkdir $HOME/.cvsq/todo

while [ $# -gt 0 ] ; do
    MY_CMD=$1

    case $MY_CMD in

    # cvsq's commands:
     --help|-h )
                 help
                 break
                 ;;

  --version|-v )
                 echo "cvsq $CVSQ_VERSION"
                 break
                 ;;

        upload ) 
                 upload_changes
                 break
                 ;;

    # CVS options

            -* )
                 CVS_OPTIONS="$CVS_OPTIONS $MY_CMD"
                 ;;

    # Commands to be executed immediately:
  update | checkout | log | login )
                 cvs $CVS_OPTIONS "$@"
                 break
                 ;;

    # Scheduled commands:
             * ) 
                 SLOT_NUM=`first_free_slot`
                 output_command cvs $CVS_OPTIONS "$@"
                 break
                 ;;
    esac
    shift
done


