#!/bin/bash

function print_usage(){
    cat <<END
Usage: $0 [-b bugs] [-d work_dir] [-m message] [-t updateType] <srpm> [scope1 [scope2 ....]]
	This command builds a package to fedora and epel releases with given srpm.

Parameters:
    -b bugs: The list of bug this update fixed. Split with ','.

    -d work_dir: The work directory. Default is current directory.

    -m message: Message used as commit message.
        If not specified, then use the latest changelog item.

	-t updateType: Update type. Valid values:
            [bugfix|security|enhancement|newpackage].
	    Default: 
	        newpackage: if this package does not exist in bodhi
		enhancement: if the latest change log item has 
		   "Enhancement:"
		bugfix: for everything else.   
       

    srpm: SRPM file to be scratch-built with koji.

    scopes: releases of what to build. Multiple values are allowed.
      Valid values:
          rawhide: Build rawhide.

          fedora: Build actives fedora releases, including Rawhide.

          fedora_1: Build the latest supported fedora releases.
              This is one release eariler than rawhide.

          fedora_2: Build the second latest supported fedora releases.
              This is two releases eariler than rawhide.

          f22 f21 ...: Build the specified fedora releases.

          epel: Build the currently supported EPEL releases.

          epel_1: Build the latest supported EPEL releases.

          epel_2: Build the second latest supported EPEL releases.

          epel7 el6 ... : The EPEL releases to be built.

         If scopes is not specified, then it works 
         as if "fedora epel" are specified.

Environment Variables:
    FEDPKG_DIR
        The directory that this program should work on.
	If -d is not specified, this program will use the value as
	work directory.

    BODHI_USER
        Bodhi username. If not specified, it uses environment variable
       	LOGNAME.


END
}

# is target been built in koji
# Valid target example: cmake-fedora-1.4.0-1.fc21
function is_target_built(){
    target=$1
    koji buildinfo $target | grep -qcs -i "State: COMPLETE"
}

# is package exists in bodhi
# Valid target example: cmake-fedora
function is_package_new_in_bodhi(){
    package=$1
    if bodhi $package | grep -qcs $package;then
	return 1
    else
	return 0
    fi
    
}

# is target in bodhi
# Valid target example: cmake-fedora-1.4.0-1.fc21
function is_target_in_bodhi(){
    target=$1
    bodhi "${target}" | grep -qcs -i "Update ID" > /dev/null
}

function is_update_enhancement(){
    echo $CHANGELOGTEXT | grep -qcs -e "Enhancement:"
}

for cmd in fedpkg bodhi koji git rpm ;do
    if ! which $cmd &>/dev/null;then
	echo "[Error] $cmd is not found in path" > /dev/stderr
	exit -2
    fi
done

SCRIPT_DIR=$(readlink -f `dirname $0`)
for d in Modules cmake-fedora/Modules ${SCRIPT_DIR}/../Modules /usr/share/cmake/Modules;do
    if [ -r $d/CmakeFedoraScript.cmake ];then
	CMAKE_FEDORA_SCRIPT_CMAKE=$d/CmakeFedoraScript.cmake
    fi
done
if [ -z "${CMAKE_FEDORA_SCRIPT_CMAKE}" ];then
    echo "[Error] CmakeFedoraScript.cmake is not found" > /dev/stderr
    exit -2
fi

CMAKE_FEDORA_KOJI_CMD=${SCRIPT_DIR}/cmake-fedora-koji
if [ ! -x ${CMAKE_FEDORA_KOJI_CMD} ];then
    echo "[Error] cmake-fedora-koji is not found" > /dev/stderr
    exit -2
fi

if [ $# = 0 ]; then
    print_usage
    exit 0
fi


BODHI_USER=${BODHI_USER:=$LOGNAME}
echo "BODHI_USER=$BODHI_USER"

WORK_DIR=${FEDPKG_DIR:-$PWD}
MSG=
BODHI_OPTS=
UPDATE_TYPE=

while getopts "hb:d:m:t:" opt;do
    case $opt in
	h)
	    print_usage
	    exit 0
	    ;;
	b )
	    BUGS=$OPTARG
	    ;;
	d )
	    WORK_DIR=$OPTARG
	    ;;
	m )
	    MSG=$OPTARG
	    ;;
	t )
	    UPDATE_TYPE=$OPTARG
	    ;;
	* )
	    ;;
	    
    esac
done
shift $((OPTIND-1)) 

SRPM=$1
shift

if [[ -z $SRPM ]];then
    print_usage
    exit -1
else
    SRPM=`readlink -f $SRPM`
fi

if [[ -n "$BUGS" ]];then
    BODHI_OPTS+=" --bugs $BUGS"
fi

if [[ ! -w $WORK_DIR ]];then
    if ! mkdir -p $WORK_DIR; then
	echo "$WORK_DIR is not writable." > /dev/stderr
	exit 2
    fi
fi
echo "WORK_DIR=$WORK_DIR" > /dev/stderr

CHANGELOGTEXT=`rpm -qp --queryformat "%{CHANGELOGTEXT}" $SRPM`

if [[ -z "$MSG" ]];then
    MSG=$CHANGELOGTEXT
fi

NAME=`rpm -qp --queryformat "%{NAME}" $SRPM`

## NVR here does not include release tag,
##  (e.g. cmake-fedora-2.0.0-1)
NVR=`rpm -qp --queryformat "%{NAME}-%{VERSION}-%{RELEASE}" $SRPM | sed -e 's/\.fc[0-9]*$//' | sed -e 's/\.el[0-9]*$//'`

if [[ -z "$UPDATE_TYPE" ]];then
    if  is_package_new_in_bodhi $NAME; then
	UPDATE_TYPE=newpackage
    elif is_update_enhancement; then
	UPDATE_TYPE=enhancement
    else
	UPDATE_TYPE=bugfix
    fi
fi
echo "UPDATE_TYPE=$UPDATE_TYPE" > /dev/stderr

cd $WORK_DIR
if [[ ! -r $NAME ]];then
    fedpkg clone $NAME
fi

if [[ ! -x $NAME ]];then
    echo "Failed to change to $WORK_DIR/$NAME" > /dev/stderr
fi

cd $NAME
fedpkg pull

first=
bodhiPushList=

for b in `$CMAKE_FEDORA_KOJI_CMD git-branch $@ | xargs `;do
    bodhi_branch=

    if [[ -z "$first" ]];then
	first=$b
    fi

    case $b in
	master )
	    bodhi_branch=`$CMAKE_FEDORA_KOJI_CMD branch rawhide | sed -e 's/^f/fc/'`
	    ;;
	f* )
	    bodhi_branch=`echo $b | sed -e 's/^f/fc/'`
	    ;;
	el* )
	    bodhi_branch=$b
	    ;;
	epel* )
	    bodhi_branch=$b
	    ;;
	* )
	    echo "Invalid branch name: $b" > /dev/stderr
	    exit 1
	    ;;
    esac

    target="$NVR.$bodhi_branch"
    fedpkg switch-branch $b
    echo -n "Has $target already been built in koji? ... " > /dev/stderr
    if is_target_built $target ;then
	echo "yes, skip this." > /dev/stderr
    else
	echo "no, start building." > /dev/stderr
	if [[ $first = $b ]];then
	    fedpkg import $SRPM
	    fedpkg commit -m "$MSG"
	else
	    git merge $first
	fi
	fedpkg push
	echo "Building $NVR.$bodhi_branch" > /dev/stderr
	fedpkg build
    fi

    if [[ ! "$b" = "master" ]];then
	echo -n "Has $target already in bodhi? ... " > /dev/stderr
	if is_target_in_bodhi $target ; then
	    echo "yes, skip this." > /dev/stderr
	else
	    echo "no, will push it." > /dev/stderr
	    bodhiPushList="$bodhiPushList $NVR.$bodhi_branch"
	fi
    fi
done

if [[ -n "$bodhiPushList" ]];then
    bodhi -n $BODHI_OPTS -t $UPDATE_TYPE -u $BODHI_USER -N "$CHANGELOGTEXT" -R testing $bodhiPushList
else
    echo "Nothing to push to bodhi." > /dev/stderr
fi

