#!/bin/sh

# Script to publish project as src.rpm on project ftp directory

# You can use this script separately in your project with
#. /usr/share/eterbuild/eterbuild
# instead follow loader

# load common functions, compatible with local and installed script
. `dirname $0`/../share/eterbuild/functions/common

load_mod spec rpm etersoft

if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
	echog "rpmpub - Etersoft specific script for publish gear repo to target ftp dir as src.rpm"
	echog "Usage: rpmpub [-f] [-r PROJECTVERSION ] [SPEC] [TARGETDIR]"
	echo
	echog "Options:"
	echog "   -f                 force set tag"
	echog "   -s                 skip set tag"
	echog "   -r PROJECTVERSION  set other project version (PROJECTVERSION/sources)"
	echog "   TARGETDIR          copy signed src.rpm package to TARGETDIR (f.i., /tmp/some_version/sources)"
	echog "                      By default used path from Source: spec field. "
	echog "                      Also you can set default target dir in ETERDESTSRPM variable."
	exit 0
fi

FORCE=
if [ "$1" = "-f" ] ; then
	FORCE=$1
	shift
fi

SETTAG=-s
if [ "$1" = "-s" ] ; then
	SETTAG=
	shift
fi

# publish to unstable by default
ALPHA=
if [ "$1" = "-r" ] ; then
	ALPHA=$2
	shift 2
fi

if [ -n "${1/*.spec/}" ] || [ -z "$1" ] ; then
	SPECNAME=$(get_gear_spec)
	echo "Using autodetected spec $SPECNAME..."
else
	SPECNAME=$1
	shift
fi

if [ ! -r "$SPECNAME" ] ; then
	fatal "Spec $SPECNAME does not found in the current dir"
fi

#Example: ETERDESTSRPM=/var/ftp/pub/Etersoft/CIFS@Etersoft/$VERSION/sources
[ -n "$ETERDESTSRPM" ] || ETERDESTSRPM="$1"

# add sources if not yet
if [ -n "$ETERDESTSRPM" ] && ! rhas "$ETERDESTSRPM" "/sources" ; then
	ETERDESTSRPM=$ETERDESTSRPM/sources
fi

if [ -z "$ETERDESTSRPM" ] ; then
	ETERDESTSRPM=$(get_etersoft_srpm_path $SPECNAME "$ALPHA")
	[ -n "$ETERDESTSRPM" ] || fatal "Can't detect target dir from spec (Url in Source: field). Run rpmpub with TARGETDIR param"
	echo "Prepare src.rpm to $ETERDESTSRPM"
else
	test -d "$ETERDESTSRPM" || fatal "You need run with exists dir to publish src.rpm project (I checked $ETERDESTSRPM, it is nonexist)"
fi
export ETERDESTSRPM

PREVPATH=$(readlink -m "$ETERDESTSRPM/../../last")
if [ -n "$ALPHA" ] && [ ! -d "$ETERDESTSRPM" ] && [ -d "$PREVPATH" ] ; then
	echo "Copying previous target tree from $PREVPATH"
	docmd cp -alv $PREVPATH $(readlink -m "$ETERDESTSRPM/..")
fi

# just for your information: rpmbs supports ssh-like target
docmd $ETERBUILDBIN/rpmbs $FORCE $SETTAG $SPECNAME || fatal "Can't build SRPMS"

# if known target and last link already exists
if [ -n "$ALPHA" ] && [ -L "$ETERDESTSRPM/../../last" ] ; then
	# set last link (assume PROJECT/VERSION/sources dir structure)
	set_last_link $ETERDESTSRPM/.. "$ALPHA"
fi
