#!/bin/bash
#
# sp_channel_stage
#
# (c) 2012 SUSE Linux GmbH, Germany.
# GNU Public License. No warranty.
#
# Version: 2013-01-28
#

C_PARENT=${2:-"sles11-sp1-pool-x86_64"}
C_SRC=${3}
C_GRP=${4}
C_OPT=${5}

echo Parent: $C_PARENT
echo Src: $C_SRC
echo GROUP: $C_GRP


function help() {
	echo "usage:    $(basename $0) OPTION"
	echo "usage:    $(basename $0) OPTION CHANNEL1 ..."
	echo
	echo " --clone PARENT SOURCE GROUP OPTION 	clone parent and all child channels"
	echo " 						PARENT: Parent Channel"
	echo " 						SOURCE: Source Channel Label"
	echo " 						GROUP: Group Name for stages"
	echo " 						OPTION: additional parametes: -wp Wait until patches are build in the new destion "
	echo " 						                                  before cloning the next stage. Don't use this   "
        echo " 										  if the source channel contains no patches !"
	echo " --list					list channels"
	echo " --delete SOURCE_GROUP			delete complete stage (01-test,02-int,03-prod)"
	echo " --version				show version"
	echo " --help					show help"
}


function wait_for_channel() {
  ERR=`spacecmd -- softwarechannel_listerrata $1 2>/dev/null | grep ^CL | wc -l` 
  while [ "$ERR" == "0" ]
    do
    ERR=`spacecmd -- softwarechannel_listerrata $1 2>/dev/null | grep ^CL | wc -l` 
     echo -n . 
     sleep 10 
    done
 echo 
  echo $ERR
}
     

# main()

case $1 in
 -l|--list)
	spacecmd -- softwarechannel_list -t
 ;;
 -c|--clone)
	# TODO shift over all args
	SRC=$C_SRC
	for C in "01-test" "02-int" "03-prod"; do
	 LAB=${C_SRC}_${C_GRP}_${C} 
	 C_UP=`echo $C |tr '[:lower:]' '[:upper:]'`
	 DST=${C_SRC}_${C_GRP}_${C_UP}
	 echo Cloning $SRC to $DST 
	 spacecmd -- softwarechannel_clone -s $SRC -n $DST -l $LAB -p $C_PARENT -g 2>/dev/null
         if [ "$C_OPT" == "-wp" ]
		then
		 echo "Waiting for patches"
	 	 wait_for_channel $LAB 
         fi
	 SRC=$LAB
         
	done
 ;;
 -v|--version)
	echo -n "$(basename $EXE) "
	head -11 $EXE | grep "^# Version: "
 ;;
 -d|--delete)
	for C in "01-test" "02-int" "03-prod"; do
	echo "Delete Channel ${2}_${C}"
	spacewalk-remove-channel -c ${2}_${C}
        done

 ;;
 -t|--test)
	echo $2
        CHN=$2
	wait_for_channel  $CHN
	echo End
 ;;
 *)
	help
 ;;
esac
#
