#!/bin/bash

if [ $# -eq 0 ]
  then
    echo "No arguments supplied"
fi
if [ $# -lt 4 ]
  then
    echo "Usage:
newbranch type versionOri versionDest pkgname 
examples:
# newbranch contribs 9 10 smeserver-mycontrib 
# newbranch sme 9 10 smeserver-package  
This script is intended to create a new branch of an existing tree by copying the content of another branch in it. You can then alter the new branch content as you want.
If you need to create the tree for the package then you should use importNew script. It will also allow you to import a srpm content.

"
        exit
fi

sme=$1
if [[ "$sme" != "sme" && "$sme" != "contribs" ]]
then
  echo "wrong first parameter should be either 'sme' or 'contribs'"
  exit
fi
re='^[0-9]+$'
if ! [[ $2 =~ $re ]] ; then
   echo "Error: Second argument should be a version number (e.g.: 9) with an existing branch (e.g.: sme9)." >&2; exit 1
fi
if ! [[ $3 =~ $re ]] ; then
   echo "Error: Third argument should be a version number (e.g.: 10) needing a new branch (e.g.: sme10)." >&2; exit 1
fi
#verd=$(($2 + 1));# rem we might want to go down too
vero=$2
verd=$3
pkgname=$4
curpwd=`pwd`
packageroot='smecontribs'
if [[ "$sme" == "sme" ]]
then
        packageroot='smeserver'
fi

cd ~/$packageroot/CVSROOT
cvs -Q update -dPA 1>/dev/null
grep -Eq "^$pkgname\s+rpms/$pkgnames.*" ~/$packageroot/CVSROOT/modules
if (( $? != 0 ))
then
        echo "Package $pkgname does not exists in modules, please create the proper tree in cvs and add it to modules. You might consider using importNew script."
        exit
fi


# if does not exist we test if it is in cvs
# if not we fail
if [ ! -d ~/$packageroot/rpms/$pkgname ]
then
        cd  ~/$packageroot/rpms
	# rem to test
        cvs -Q -z3 -d:ext:shell.koozali.org:/cvs/$packageroot co -P $pkgname #1>/dev/null

        if [ !  -d ~/$packageroot/rpms/$pkgname ]
        then
                echo "no such module $pkgname"
		exho "use instead importNew script"
                exit;
        fi
fi

cd ~/$packageroot/rpms;
cvs update -dPA $pkgname >/dev/null

if [ ! -d ~/$packageroot/rpms/$pkgname/$sme$vero ]
	then
		echo "Branch $sme$vero does not exist. Nothing to do.";
		exit;
	fi

if [ -d ~/$packageroot/rpms/$pkgname/$sme$verd ]
	then
		echo "Branch $sme$verd exists. Nothing to do.";
	else
		cd  ~/$packageroot/rpms
		rm -rf ~/$packageroot/rpms/$pkgname
		cd ~/$packageroot/rpms
		cvs -Q co $pkgname
		cd $pkgname
		# then you can copy 
		cp -a $sme$vero $sme$verd
		rm -rf $sme$verd/CVS
		cvs add $sme$verd
		cd $sme$verd
		find ./ -name CVS -prune -o -print | xargs cvs add
		cvs commit -m 'Initial import'
		echo "# then you have to do:"
		echo "cd ~/$packageroot/rpms/$pkgname/$sme$verd/"
		echo "make local"
		echo "make tag ;make build"
                echo "# Alternatively you can do:"
                echo "# make mockbuild"
                echo "# make tag ;make build"
	fi


