#!/bin/bash
# 2005-2006, 2009, 2014, 2015 (c) Etersoft www.etersoft.ru
# 2005-2015 Author: Vitaly Lipatov <lav@etersoft.ru>
# Public domain
#
# GS - get source
#
# Скачивает исходники, автоматически выправляя ситуацию с gz/bz2/tgz/zip (tar для git, tar.bz2 для src.rpm)
# Параметры:
# - название спек-файла
# -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 tarball web buildsrpm

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

#############################
Usage="Usage: $name [-a -f ] [spec] [new_version]"
function mygetopts()
{
name=${0##*/}
Descr="$name (Get Source) - get sources by spec / repository"

phelp()
{
	echog "$Descr"
	echog "$Usage"
	echog "You can run 'rpmgs 1.2' for set new version 1.2 and download it"
	echo
	echog "Options:"
	echog "   -a  get all source (not only Source|Source0)"
	echog "   -f  force download (remove source file 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=-f ;;
    +?) 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=$@

}

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

repack_tarball()
{
	[ "$(realpath "$1")" = "$(realpath "$2")" ] && return
	docmd erc -f repack "$1" "$2"
}

download_any_tarball()
{
	local GETSOURCE="$1"
	local TARGET="$2"
	local ext
	local FORMATS="tar.xz tar.bz2 tar.gz zip tgz 7z tbz2 tbz rar tar"
	local BASESOURCE="$GETSOURCE"
	# drop any ext
	for ext in $FORMATS ; do
		BASESOURCE=$(echo "$BASESOURCE" | sed -e "s|\.$ext$||g")
	done
	# try download with some ext
	for ext in $FORMATS ; do
		[ -n "$FORCEDOWNLOAD" ] && docmd rm -f "$BASESOURCE.$ext"
		download_url "$BASESOURCE.$ext" || continue
		repack_tarball "$(basename "$BASESOURCE.$ext")" "$TARGET" || continue
		return
	done
	fatal "Cannot retrieve $GETSOURCE"
}

# param: spec name number (f.i., url for Source-url)
function source_ext()
{
	local GETSOURCEEXT=
	# %define SourceUrl ftp://updates.etersoft.ru/pub/Etersoft/WINE@Etersoft/last/sources/tarball/%name-%version.tar.gz
	#GETSOURCEURL=$(eval_spec $1 | grep -i "^%define ${2}Url${3} " | head -n 1 | sed -e "s/ *\$//g" | sed -e "s/^%define[ \t].*[ \t]//g")
	if grep -q "# Source$3-$2:" "$1" ; then
		local TMPSPEC=$1.tmpurl
		local NEWSOURCE=$(grep "# Source$3-$2:" "$1" | sed -e "s/.*$2:[ \t]*//g")
		test -n "$NEWSOURCE" || fatal "Can't extract URL from $Source$3-$2"
		# Fake replace for correct subst variables
		NEWSOURCE="$(echo "$NEWSOURCE" | sed -e 's|\&|\\&|g')"
		# TODO: use special field before %build
		cat $1 | sed -e "s|^Summary:.*|Summary: $NEWSOURCE|g" > $TMPSPEC
		GETSOURCEEXT=$(eval_spec "$TMPSPEC" | get_var "Summary")
		rm -f "$TMPSPEC"
	fi
	echo "$GETSOURCEEXT"
	test -n "$GETSOURCEEXT"
}


# Source-svn: http://svn.wikimedia.org/svnroot/mediawiki/trunk/extensions/Collection/
function get_source_svn()
{
	GETSOURCESVN=$(source_ext "$1" svn "$2")
	#if [ -n "$GETSOURCESVN" ] ; then
	#	warning "Source-svn is not supported yet"
	#	( cd $SPECDIR ; git svn clone $GETSOURCESVN .)
	#fi
	#test -n "$GETSOURCESVN"
}


# Source-git: http://git.altlinux.org/people/lav/packages/rpm-build-fonts.git
function get_source_git()
{
	fatal "realize me"
}

# Source-url: ftp://updates.etersoft.ru/pub/Etersoft/WINE@Etersoft/last/sources/tarball/%name-%version.tar.gz
# Get real Url from comment
function get_source_url()
{
	GETSOURCEURL=$(source_ext "$1" url "$2")
}

function print_error()
{
	echog "Can't find any spec file. It is possible you run this script not in git dir."
	echog "If you use old style build, run rpmgs with spec name as arg."
	echog "If you wish download src.rpm, use rpmgp script."
	exit 1
}

# tarball dirname [options]
gear_update_from_tarball()
{
	local CREATEFLAG=-f
	local TARBALL="$1"
	local CURNAME="$2"
	shift 2
	[ -d "$CURNAME" ] || CREATEFLAG=-c
	# TODO: check tarball ext. for unsupported arch and realize it here or in gear-update
	echo "Commit tarball '$TARBALL' to git subdir '$CURNAME'..."
	if ! docmd gear-update $CREATEFLAG $@ "$TARBALL" "$CURNAME" ; then
		if gear-update $CREATEFLAG $@ "$TARBALL" "$CURNAME" 2>&1 | grep -q "More than one subdirectory specified" ; then
			echo "Try unpack as is"
			CREATEFLAG="$CREATEFLAG -a"
			docmd gear-update $CREATEFLAG $@ "$TARBALL" "$CURNAME" && return
		fi
	else
		return 0
	fi
	fatal "can't import tarball '$TARBALL'"
}

parse_cmd_pre_spec "$@"
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 spec in $LISTNAMES
do
	if [ -n "${spec/*spec/}" ] ; then
		print_error
	fi

	set_specdir $spec

	# Set version if needed
	if [ -n "$GSSETVERSION" ] ; then
		CURVER=$(get_version $spec)
		set_version $spec $GSSETVERSION
		if [ "$CURVER" != "$GSSETVERSION" ] ; then
			set_release $spec $GSSETRELEASE
			if [ -n "$GSSETRELEASE" ] ; then
				echo "Set new $GSSETVERSION-$GSSETRELEASE version for $spec"
			else
				echo "Set new $GSSETVERSION version for $spec"
			fi
		else
			echo "Version $GSSETVERSION already was set"
			GSSKIPADDCHANGELOG=1
		fi
	fi

	for nn in "" $LOADLIST
	do
		get_source $spec "Source$nn"
		[ "$GETSOURCE$nn" = "0" ] && continue
		test -z "$GETSOURCE" && { echog "Skip Source${nn} from $spec" ; continue ; }
		FTB=`basename "$GETSOURCE"`
		# for get RPMSOURCEDIR
		build_rpms_name $spec

		# TODO: do not use RPMSOURCEDIR for temp. tarballs
		[ -n "$FORCEDOWNLOAD" ] && rm -f "$RPMSOURCEDIR/$FTB"
		#[ -f "$RPMSOURCEDIR/$FTB" ] && { echog "Tarball $FTB already exists in $RPMSOURCEDIR dir, skipping." ; continue ; }

		# TODO: dropout these pushd/popd
		# use pushd/popd due several cd / cd -
		mkdir -p $RPMSOURCEDIR/ && pushd $RPMSOURCEDIR/ >/dev/null || fatal "Can't create/chdir..."

		# Test for eterbuild extensions (will set GETSOURCEURL or GETSOURCESVN)
		get_source_url $spec $nn || get_source_svn $spec $nn

		if ! rhas "$GETSOURCE" ".tar$" ; then
			warning "It is recommended to use .tar tarballs for sources ($FTB now)"
		fi

		if [ -n "${GETSOURCESVN}" ] ; then
			is_gear $SPECDIR || fatal "Source-svn works only with gear repo"
		# TODO: GETSOURCEGIT
		# TODO: rewrite code to use original file format and temp. download dir
		elif [ -n "${GETSOURCEURL}" ] ; then
			echog "Try to load ${GETSOURCEURL} for $spec"
			download_url "$GETSOURCEURL" || fatal "Can't download $GETSOURCEURL"
			# FIXME: gear-update can use any tarball
			repack_tarball "$(basename "$GETSOURCEURL")" "$FTB"
		else
			rhas "$GETSOURCE" "ps?://" || fatal "$GETSOURCE is not URL"
			download_any_tarball "$GETSOURCE" "$FTB"
		# TODO: fix download single packed file
		#else
		#		download_url "$GETSOURCE"
		fi

		echog "DONE with $FTB"
		popd >/dev/null

	done

	if [ -z "$GSSKIPADDCHANGELOG" ] ; then
		# Write changelog if all done
		CURVER=$(get_version $spec)
		CURREL=$(get_release $spec)
		EGEARME=""
		is_gear && EGEARME=" with rpmgs script"
		add_changelog_helper "- new version ($CURVER)$EGEARME" $spec || echog "Changelog entry for $CURVER-$CURREL already exists"
	fi

	if [ -n "$GSSETVERSION" ] || [ -n "$FORCEDOWNLOAD" ]; then
		if [ -n "${GETSOURCESVN}" ] ; then
			# clone svn repo to current dir
			# FIXME: need to clone in git root dir
			GITROOT=.
			[ $(basename `pwd`) = ".gear" ] && GITROOT=../
			docmd git svn clone $GETSOURCESVN $GITROOT
			echo "Run svn rebase from $GETSOURCESVN"
			docmd git svn rebase
		elif is_gear ; then
			CURNAME=$(get_tardir_from_rules) || fatal "There is no 'tar:' line in gear rules file or 'tar: .' used"
			test -d "$CURNAME" || CURNAME=$(get_tarballname "$spec")
			test -d "$CURNAME" || CURNAME=$BASENAME
			gear_update_from_tarball "$RPMSOURCEDIR/$FTB" "$CURNAME" $FORCEDOWNLOAD
			rm -f "$RPMSOURCEDIR/$FTB"
			docmd git commit -m "just import $FTB with rpmgs script"
		fi
	else
		is_gear && echo "Skip tarball committing (run with version or with -f option)."
	fi
done

exit 0

