#!/bin/bash
# 2008 Etersoft www.etersoft.ru
# Author: Vitaly Lipatov <lav@etersoft.ru>
# Public domain


# Universal rpmbuild function
# 1st: rpmbuild, hsh, buildreq
# 2nd: spec name(s) (only one if git, we will skip it)
# other parameters
uni_rpmbuild()
{
	local RET=0
	# hack due quotes
	# just for fill by something
	local ONEPARAM="-v"
	local TWOPARAM="-v"

	local SPECNAME=$1
	local SPECDIR=`dirname $SPECNAME`
	local GEAR=gear

	if [ -n "$USE_LEGACY_COMPRESSION" ] ; then
		# FIXME: do not override -v
		ONEPARAM="--define=_source_payload w9.gzdio"
	fi
	
	if [ -n "$RPMTOPDIR" ] ; then
		TWOPARAM="--define=_topdir $RPMTOPDIR"
	fi

	if is_gear $SPECDIR ; then
		[ -f "$SPECNAME" ] || fatal "run uni_rpmbuild with spec as 2nd parameter"
		shift # skip spec name
		#[ -n "$SPECDIR" ] && [ "$SPECDIR" != "." ] && warning "Spec is not in git dir (SPECDIR='$SPECDIR')"
		# build package without MENV checking
		if true || [ "$MENV" = "SS" ] ; then
			$NICE $GEAR --commit --rpmbuild -- $RPMBUILD "$ONEPARAM" "$TWOPARAM" $@ || RET=$?
		else
			fatal "Build backported src.rpm from git is unsupported now"
			# build src.rpm via hasher (on ALT)
#			$NICE gear-hsh --build-args="-bs" --rpmbuild -- $COMMAND "$ONEPARAM" $@
			$NICE $GEAR --hasher -- myhsh --build-prog=$ETERBUILDDIR/functions/rebuild $@ || RET=$?
		fi
	else
		mkdir -p $RPMTOPDIR/BUILD $RPMTOPDIR/SRPMS
		$NICE $RPMBUILD "$ONEPARAM" "$TWOPARAM" $@ || RET=$?
	fi
	[ -n "$VERBOSE" ] && echo "Run $RPMBUILD $ONEPARAM $TWOPARAM $@" || :
	return $RET
}


uni_buildreq()
{
	local RET=0
	local SPECNAME=$1
	local SPECDIR=`dirname $SPECNAME`
	local GEARBUILDREQ=gear-buildreq

	if is_gear $SPECDIR ; then
		$NICE $GEARBUILDREQ --commit -- $@ || RET=$?
	else
		$NICE buildreq $@ || RET=$?
	fi
	return $RET
}

uni_rpminstall()
{
	local RET=0
	local TWOPARAM="-v"

	if [ -n "$RPMTOPDIR" ] ; then
		TWOPARAM="--define=_topdir $RPMTOPDIR"
	fi

	#if is_gear $SPECDIR ; then
	#	$NICE $GEARBUILDREQ --commit -- $@ || RET=$?
	#else
		echo -n "Install package "
		mkdir -p $RPMTOPDIR/SOURCES $RPMTOPDIR/SRPMS $RPMTOPDIR/RPMS
		rpm -iv "$TWOPARAM" $@ || RET=$?
	#fi
	return $RET
}

# get correct BUILDROOT, run build_rpms_name before!
build_buildroot()
{
	test -z "$BASENAME" && fatal "Use build_buildroot with BASENAME defined"
	# ALT Only?
	BUILDROOT=`rpm --eval %buildroot | subst_namever`
	test -z "$BUILDROOT" && fatal "Fix rpm's buildroot"
	if [ "$BUILDROOT" = "%buildroot" ] ; then
		BUILDROOT="$HOME/tmp/$BASENAME-buildroot"
		warning "Can't get buildroot from RPM, set to $BUILDROOT"
		return 1
	fi
	return 0
}

#      .
#   !
#    Name:   
# TODO:     NAMESPEC,   SPECNAME

build_rpms_name()
{
	local tmprpm CATSPEC NAMESPEC PKGARCH
	#TODO change : to = and execute?
	NAMESPEC=$1
	shift
	test -f "$NAMESPEC" || fatal "Spec $NAMESPEC does not exist"

	tmprpm=`make_temp_file $NAME`
	# Optimization
	eval_spec $NAMESPEC $@ | grep ":"  >$tmprpm
	BASENAME=$(cat $tmprpm | get_var "Name")
	RELEASE=$(cat $tmprpm | get_var "Release")
	VERSION=$(cat $tmprpm | get_var "Version")
	TARBALLNAME=$(cat $tmprpm | get_var "Source.*")
	[ -n "$TARBALLNAME" ] && TARBALLNAME=$(basename $TARBALLNAME)

	PKGARCH=$(cat $tmprpm | get_var "BuildArch")
	if [ "$PKGARCH" != "noarch" ] ; then
		PKGARCH=$DEFAULTARCH
	fi
	NAMERPMIN=$BASENAME-$VERSION-$RELEASE.$PKGARCH.rpm
	NAMESRPMIN=$BASENAME-$VERSION-$RELEASE.src.rpm

	RPMSOURCEDIR=`rpm --eval %_sourcedir | subst_namever`
	[ -n "$RPMSOURCEDIR" ] || fatal "Can't detect RPM/SOURCES dir"

	local BNS NSS
	BNS="$BASENAME".spec
	NSS=`basename $NAMESPEC`
	test "$NSS" != "$BNS" && warning "Spec name ($NSS) is not equal to Name of package ($BNS)"
	rm -f $tmprpm

	build_buildroot
}

# LISTNAMES, options in arg
pack_src_rpm()
{
local i
ARGS=$@
# NOTE: always nodeps
# enable --nodeps for other ENV
#test -n "$MENV" && 
[ -n "$VERBOSE" ] && echo "LISTNAMES=$LISTNAMES ARGS=$ARGS" || :
ARGS="$ARGS --nodeps"
for i in $LISTNAMES
do
	
	if [ -z ${i/*rpm/} ] ; then
		# if rpm not spec, guess it is src.rpm
		NAMESRPMIN=$(basename $i)
	else
		#     
		# BASENAME, RELEASE, VERSION, NAMESRPMIN, NAMERPMIN
		build_rpms_name "$i" $ARGS
		if [ -n "${SIGN}" ]; then
			echog "Try to packing \$NAMESRPMIN package for sign"
			add_changelog $i
			if [ $? = "0" ]; then
				echog "Spec file \$i had not ChangeLog entry. It have added now, check it and enter your command again."
				echog "Wait for ten seconds."
				sleep 10
				exit 1
			fi
			uni_rpmbuild $i -bs $ARGS $NODEPS --target $DEFAULTARCH
		else
			echog "Just packing \$NAMESRPMIN"
			uni_rpmbuild $i -bs $ARGS $NODEPS --target $DEFAULTARCH || fatal "Error with rpmbuild"
		fi
	fi
	
	# Check the package really built
	if [ -f $RPMTOPDIR/SRPMS/$NAMESRPMIN ] ; then
		LISTBUILT="$LISTBUILT $NAMESRPMIN"
	else
		fatal "Can't find '$NAMESRPMIN' in '$RPMTOPDIR/SRPMS'"
	fi
done
# remove extra space before list
LISTBUILT=$(echo "$LISTBUILT" | sed -e "s|^ ||")
test -z "$LISTBUILT" && fatal "Error: List for build is empty. Check if file is exist."
#LISTRPMARGS=`echo ${LISTRPMARGS} | sed -e "s/--nodeps//g"`
}

# build binary package list (1st - repo dir, 2st - pkgname)
# algorithm: list all files in PKGDIR, print packages with our source pkg name
get_binpkg_list()
{
	local PKGDIR=$1
	local PKGNAME=$(basename $2)
	find "$PKGDIR" ! -name '*\.src\.rpm' -name '*\.rpm' -execdir \
		rpmquery -p --qf='%{sourcerpm}\t%{name}-%{version}-%{release}.%{arch}.rpm\n' "{}" \; \
		| grep "^$PKGNAME[[:space:]].*" | cut -f2 | xargs -n1 -I "{}" echo "$PKGDIR/{} "
}

drop_pkg_extensions()
{
	for i in $@ ; do
		echo -n "$(basename $i) " | sed -e "s|\.[a-z0-9]*\.rpm||g"
	done
}

check_log()
{
	local LOGFILE i RES
	echo
	echo "-------------------------------------------------------"
	echog "Check log for..."
	LOGFILE=$1
	grep 'ld: warning: libstdc++\.so\.5, needed by [^ ]\+, may conflict with libstdc++\.so\.6' $LOGFILE
	RES=$?
	if [ $RES = 0 ] ; then
		echog "Error: libstdc++.so.5/6 conflicts"
		return 1
	fi
	grep 'python-strict' $LOGFILE && warning "python-strict used!!!"
	NC1="command not found"
	NC2="-march=athlon -mtune=athlon-xp"
	#for i in ${NC1} ; do
	grep -- '$NC1' $LOGFILE && warning "'$NC1' in build output (some errors in a scripts)"
	grep -- '$NC2' $LOGFILE && warning "'$NC2' in build output (forbidden) "
	#done
	return 0
}

