#!/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.

          el7 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
# Valid target example: cmake-fedora-1.0.5-1.fc20
function is_target_built(){
    target=$1
    ${KOJI_CMD} 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_CMD} $package | grep -qcs $package;then
	return 1
    else
	return 0
    fi
    
}

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

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

for f in /etc/cmake-fedora.conf $PWD/cmake-fedora.conf; do
    if [ -e $f ];then
	source $f
    fi
done

for p in $CMAKE_FEDORA_LIBEXEC_DIR $PWD $PWD/scripts ;do
    FUNCTION_FILE=$p/cmake-fedora-functions
    if  [ -r $FUNCTION_FILE ];then
	source $FUNCTION_FILE
	break
    fi
done

RPM_CMD=`find_program rpm`
FEDPKG_CMD=`find_program fedpkg`
KOJI_CMD=`find_program koji`
GIT_CMD=`find_program git`
BODHI_CMD=`find_program bodhi`
BODHI_USER=${BODHI_USER:=$LOGNAME}
echo "BODHI_USER=$BODHI_USER"

SCRIPT_DIR=$(realpath `dirname $0`)
CMAKE_FEDORA_KOJI_CMD=`find_program cmake-fedora-koji $SCRIPT_DIR`

WORK_DIR=${FEDPKG_DIR:-$PWD}
MSG=
BUGS=
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=`realpath $SRPM`
fi

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

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

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

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

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

## NVR here does not include release tag,
##  (e.g. cmake-fedora-2.0.0-1)
NVR=`${RPM_CMD} -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_CMD clone $NAME
fi

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

cd $NAME
${GIT_CMD} pull --all

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
	    ;;
	* )
	    echo "Invalid branch name: $b" > /dev/stderr
	    exit 1
	    ;;
    esac

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

    fi

    if [[ ! "$b" = "master" ]];then
	echo -n "Has $target already in bodhi? ... "
	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

echo "Running $BODHI_CMD -n $BUGS -t $UPDATE_TYPE -u $BODHI_USER -N \"$CHANGELOGTEXT\" -R testing $bodhiPushList"
if [[ -n "$bodhiPushList" ]];then
    $BODHI_CMD -n $BUGS -t $UPDATE_TYPE -u $BODHI_USER -N "$CHANGELOGTEXT" -R testing $bodhiPushList
fi

