#!/bin/sh
# 2005-2006, 2009 (c) Etersoft www.etersoft.ru
# Author: Vitaly Lipatov <lav@etersoft.ru>
# Public domain
#
# GS - get source
#
#  ,     gz/bz2/tgz/zip
# :
# -  -
# TODO: -h (build in hasher), -s (sign for upload)
# -a - get all source
# check for the same file with other compression

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

WEXT=""
GETSOURCE=""
LOADLIST="0"

#############################
Usage="Usage: $name [-a -r ] spec ... | spec new_version"
function mygetopts()
{
name=${0##*/}
Descr="$name - get sources for spec"

phelp()
{
	echog "$Descr"
	echog "$Usage"
	echog "You can run rpmgs file.spec new_version for set new version and download it"
	echog "Options:"
	echog " -a - get all source (not only 0)"
	echog " -f - force download (remove source before download)"
}

while getopts :haf opt; do
    case $opt in
    h) phelp; exit 0;;
    a) LOADLIST=" 0 1 2 3 4 5 6 7 8" ;;
	f) FORCEDOWNLOAD=1 ;;
    +?) echog "$name: options should not be preceded by a '+'." 1>&2; exit 2;;
    ?)  echog "$name: $OPTARG: bad option.  Use -h for help." 1>&2 ; exit 2;;
    esac
done
 
# remove args that were options
shift $((OPTIND - 1))

LISTRPMARGS=$@

}

get_tarball()
{
	# use wget with try=1 and timeout = 30 sec
	wget -c -t 1 -T 30 "$1"
}


get_archive()
{
	#TODO: check for gz
	URL=${GETSOURCE/.tar.bz2/}
	[ "$URL" = "$GETSOURCE" ] && URL=${GETSOURCE/.tar/}
	get_tarball "$URL.$1" || return
	WEXT=`basename "$URL"`
	test -f "$WEXT.$1" || return
	[ "$1" = "tar.bz2" ] || echog -n "Converting to $WEXT.tar..."
}

get_archive1()
{
	#TODO: check for gz
	URL=${GETSOURCE/.bz2/}
	get_tarball "$URL$1" || return
	WEXT=`basename "$URL"`
	test -f "$WEXT" || return
	echog -n "Converting to $WEXT.bz2..."
}

bzipit()
{
	locale PBZIPIT
	PBZIPIT=`which pbzip2 2>/dev/null`
	if [ -n "$PBZIPIT" ] ; then
		echog -n " with pzip2..."
		$PBZIPIT -9 -f $1
		return $?
	else
		echog -n " with bzip2..."
		bzip -f --best $1
		return $?
	fi
}

get_tarbz2()
{
	get_archive tar.bz2
	return $?
}

get_bz2()
{
	get_archive1 .bz2
	return $?
}

function get_gz()
{
	get_archive1 .gz || return $?
	gunzip -f $WEXT.gz
}

function get_raw()
{
	get_archive1 "" || return $?
	test -f $WEXT
}


function get_targz()
{
	get_archive tar.gz || return $?
	#gzip -t $WEXT.tar.gz || return
	gunzip -f $WEXT.tar.gz
}

function get_tar()
{
	get_archive tar || return $?
	test -f $WEXT.tar
}

function get_tgz()
{
	get_archive tgz || return $?
	gunzip -f $WEXT.tgz
}

function get_tbz2()
{
	get_archive tbz2 || return $?
	mv -f $WEXT.tbz2 $WEXT.tar.bz2
}

function get_tbz()
{
	get_archive tbz || return $?
	mv -f $WEXT.tbz $WEXT.tar.bz2
}

# TODO: use external converter
function get_zip()
{
	get_archive zip || return $?
	mkdir $WEXT.zip.dir || return $?
	cd $WEXT.zip.dir
	unzip -q ../$WEXT.zip && tar cf ../$WEXT.tar . || return
	cd ..
	rm -rf $WEXT.zip.dir
}

# TODO: use external converter
function get_7z()
{
	BIN7ZIP=/usr/bin/7z
	test -x $BIN7ZIP || return $?
	get_archive 7z || return $?
	mkdir $WEXT.7z.dir || return $?
	cd $WEXT.7z.dir
	$BIN7ZIP x ../$WEXT.7z && tar cf ../$WEXT.tar . || return
	cd ..
	rm -rf $WEXT.7z.dir
}

function dir_name()
{
	rm .listing
	#wget `dirname $MAINSOURCE` --dont-remove-listing
	
}

function get_source()
{
	GETSOURCE=$(eval_spec $1 | get_var "$2")
}

function print_error()
{
	echog "You have no spec files as arg"
	echog "Please use for spec files only. If you wish to download src.rpm, use rpmgp script."
	exit 1
}

parse_cmd_pre "$@"
mygetopts $LISTARGS

test -z "$VERBOSE" || echo "'$LISTNAMES' @ '$LISTRPMARGS'"

if [ -n "$LISTRPMARGS" ] ; then
	if [ -z "${LISTRPMARGS/*spec/}" ] ; then
		fatal "run with incorrect filename $LISTRPMARGS"
	fi
	if [ ! -f "$LISTNAMES" ] ; then
		fatal "set version permitted only for one file"
	fi
	if [ "${LISTRPMARGS/ /}" != "$LISTRPMARGS" ] ; then
		fatal "you run rpmgs with more than one version"
	fi
	GSSETVERSION=$LISTRPMARGS
fi

test -z "$LISTNAMES" && print_error

[ -z "$GSSETRELEASE" ] || GSSKIPADDCHANGELOG=1

for i in $LISTNAMES
do
	if [ -n "${i/*spec/}" ] ; then
		print_error
	fi
	
	#set_specdir $i
	SPECDIR=`pwd`
	# Set version if needed
	if [ -n "$GSSETVERSION" ] ; then
		CURVER=$(get_version $i)
		set_version $i $GSSETVERSION
		if [ "$CURVER" != "$GSSETVERSION" ] ; then
			[ -n "$GSSETRELEASE" ] || GSSETRELEASE=alt1
			set_release $i $GSSETRELEASE
			echo "Set new $GSSETVERSION-$GSSETRELEASE version for $i"
		else
			echo "Version $GSSETVERSION already set"
			GSSKIPADDCHANGELOG=1
		fi
	fi

	for nn in "" $LOADLIST
	do
		get_source $i "Source$nn"
		test -z "$GETSOURCE" && { echog "Skip Source${nn} from $i" ; continue ; }
		FTB=`basename "$GETSOURCE"`
		# for get RPMSOURCEDIR
		build_rpms_name $i
		[ -n "$FORCEDOWNLOAD" ] && rm -f "$RPMSOURCEDIR/$FTB"

		if [ -z "${GETSOURCE/*.tar/}" ] && is_gear $SPECDIR; then
			test -f "$RPMSOURCEDIR/$FTB" && { echog "Tarball $FTB already exists in SOURCES dir, skipping." ; continue ; }
		else
			bzip -t "$RPMSOURCEDIR/$FTB" && { echog "Tarball $FTB already exists in SOURCES dir, skipping." ; continue ; }
		fi

		mkdir -p $RPMSOURCEDIR/ && pushd $RPMSOURCEDIR/ || fatal "Can't create/chdir..."
		echog "Try to load $GETSOURCE for $i"
		#if is_gear $SPECDIR && [ -n "${GETSOURCE/*.tar/}" ] ; then
		#	warning "It is recommended to use .tar tarballs for sources in gear"
		#	get_tarball "$GETSOURCE"
		if [ -n "${GETSOURCE/*.bz2/}" ] && ! is_gear $SPECDIR ; then
			warning "It is recommended to use .bz2 tarballs for sources in rpm"
			get_tarball "$GETSOURCE"
		elif [ -n "${GETSOURCE/*.tar.bz2/}" ] && ! is_gear $SPECDIR ; then
			warning "It is not tarball (possible single file)..."
			get_bz2 || get_gz || get_raw || fatal "Error: Cannot retrieve $GETSOURCE"
		else
			if [ -z "${GETSOURCE/*.tar/}" ] && is_gear $SPECDIR; then
				echo "Get tarball for gear"
				FORGEAR=1
			fi
			get_tarbz2 || get_targz || get_tgz || get_7z || get_zip || get_tbz2 || get_tbz || get_tar || dir_name || fatal "Error: Cannot retrieve $GETSOURCE"
		fi

		if [ -z "$FORGEAR" ] ; then
			echog -n "Compressing to $WEXT.tar.bz2..."
			test -f $WEXT.tar.bz2 || bzipit $WEXT.tar || fatal "Error: Cannot bzip $WEXT.tar"
		fi

		echo "DONE"
		popd

	done

	if [ -z "$GSSKIPADDCHANGELOG" ] ; then
		# Write changelog if all done
		CURVER=$(get_version $i)
		CURREL=$(get_release $i)
		EGEARME=""
		is_gear && EGEARME="import in git"
		add_changelog_helper "- new version ($CURVER) $EGEARME" $i || echog "Changelog entry for $CURVER-$CURREL already exists"
	fi
	if [ -n "$GSSETVERSION" ] && is_gear ; then
		CURNAME=$(get_tarballname $i)
		echo "Commit tarball $RPMSOURCEDIR/$FTB to git subdir '$CURNAME'..."
		gear-update "$RPMSOURCEDIR/$FTB" "$CURNAME"
		git commit -m "just import $(basename $RPMSOURCEDIR/$FTB)"
	else
		is_gear && echo "Run without version. Skip tarball commiting."
	fi
done

exit 0

