#!@@SH@@
#
# opkbuild
# src/ob-unpacksource
# Unpack native or upstream source.
#
# Copyright (C) 2012 Patrick "P. J." McDermott
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

. '@@LIBOPKBUILD@@/load.sm'

ob_use locale
ob_use output
ob_use package

upstream_ar_base=
upstream_ar=
upstream_ar_z=
upstream_ar_dir=

main()
{
	ob_set_text_domain 'opkbuild'

	ob_init_package '..'
	ob_parse_package_metadata -c '.opkbuild.cache'

	if [ -d 'src' ]; then
		ob_info "$(ob_get_msg 'already_unpacked')"
	else
		if [ -d '../src' ]; then
			unpack_native
		elif get_upstream_archive; then
			unpack_upstream
		fi
	fi
}

unpack_native()
{
	ob_info "$(ob_get_msg 'unpacking_native')"
	cp -Rp '../src' 'src' || ob_error "$(ob_get_msg 'cant_unpack_native')"
}

unpack_upstream()
{
	get_upstream_compression
	get_upstream_dir
	extract_upstream
}

get_upstream_archive()
{
	upstream_ar_base="${OPK_SOURCE}-${OPK_SOURCE_VERSION_UPSTREAM}.orig.tar"
	upstream_ar="$(find '..' -name "${upstream_ar_base}*")"
	case "$(echo "${upstream_ar}" | grep -v '^$' | wc -l)" in
		0)
			ob_info "$(ob_get_msg 'no_sources')"
			return 1
			;;
		1)
			return 0
			;;
		*)
			ob_error "$(ob_get_msg 'multiple_upstream_sources')"
			;;
	esac
}

get_upstream_compression()
{
	z_ext="${upstream_ar#../${upstream_ar_base}}"
	case "${z_ext}" in
		'')
			upstream_ar_z=''
			;;
		'.gz')
			upstream_ar_z='z'
			;;
		'.bz2')
			upstream_ar_z='j'
			;;
		'.lz')
			upstream_ar_z='a'
			;;
		'.Z')
			upstream_ar_z='Z'
			;;
		*)
			ob_error "$(ob_get_msg 'unsupported_archive_compression')" \
				"${z_ext}"
			;;
	esac
}

get_upstream_dir()
{
	upstream_ar_dir="$(tar "-t${upstream_ar_z}f" "${upstream_ar}" | \
		sed -n 's@^\(\./\|\)\([^/]*\)\(/\|\).*$@\2@p' | sort | uniq)"
	case "$(echo "${upstream_ar_dir}" | grep -v '^$' | wc -l)" in
		0)
			ob_error "$(ob_get_msg 'no_upstream_dirs')"
			;;
		1)
			;;
		*)
			ob_error "$(ob_get_msg 'multiple_top_upstream_dirs')"
	esac
}

extract_upstream()
{
	ob_info "$(ob_get_msg 'unpacking_upstream')"
	tar "-x${upstream_ar_z}f" "${upstream_ar}" || \
		ob_error "$(ob_get_msg 'cant_unpack_upstream')"
	mv "${upstream_ar_dir}" 'src' || \
		ob_error "$(ob_get_msg 'cant_move_native')"
}

main "${@}"