#!/bin/sh
# --- SDE-COPYRIGHT-NOTE-BEGIN ---
# This copyright note is auto-generated by ./scripts/Create-CopyPatch.
#
# Filename: bin/sde-list-download
# Copyright (C) 2007 - 2008 The OpenSDE Project
#
# More information can be found in the files COPYING and README.
#
# 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; version 2 of the License. A copy of the
# GNU General Public License can be found in the file COPYING.
# --- SDE-COPYRIGHT-NOTE-END ---

[ -n "$SDEROOT" ] ||
	export SDEROOT=$( cd "${0%/*}/.."; pwd -P )

. $SDEROOT/lib/libsde.in

list_usage() {
	local progname=${0##*/}
	cat <<EOT
Usage:	$progname [--cfg <config>] [-erkl] [ITEMS...]
EOT
}

shortopts='c:erpkl'
longopts='cfg:,extenders,repositories,package,checksum,location'
options=$( getopt -o "$shortopts" -l "$longopts" -- "$@" )
if [ $? -ne 0 ]; then
	list_usage
	exit -1
fi

# load new arguments list
eval set -- "$options"

config=
extenders=
repositories=

want_package=
want_checksum=
want_location=

while [ $# -gt 0 ]; do
	case "$1" in
		--)		shift; break ;;

		-c|--cfg)	shift; config="$1" ;;

		-e|--extenders)
			extenders=yes ;;
		-r|--repositories)
			repositories=yes ;;

		-p|--package)	want_package=yes ;;
		-k|--checksum) 	want_checksum=yes ;;
		-l|--location)	want_location=yes ;;
	esac
	shift
done

# TODO: target/$target/download.txt

$SDEROOT/bin/sde-list-pkg ${config:+-c $config} ${extenders:+-e} ${repositories:+-r} -- "$@" | while read descfile; do
	pkg=$( echo "$descfile" | cut -d/ -f3 )
	grep '^\[D\]' $SDEROOT/$descfile | while read x cksum gzfile location; do
		output=

		# package name
		[ -z "$want_package" ] || output="$pkg"

		# checksum
		[ -z "$want_checksum" ] || output="${output:+$output\t}$cksum"

		# destination file

		if [ "$location" != "${location#-}" ]; then
			mirror=local
			location="${location#-}"
		else
			mirror=mirror
		fi

		bz2file=$( echo "$gzfile" | sed -e 's,\.gpg$,,' -e 's,\.\(t\?\)\(gz\|Z\)$,.\1bz2,' -e 's,\.tar$,.tar.bz2,' )
		output="${output:+$output\t}download/$mirror/${bz2file:0:1}/$bz2file"

		# source location
		if [ -n "$want_location" ]; then
			if [ "$location" != "${location#!}" ]; then
				# keep untouched
				source="${location#!}"
			elif [ "$location" = "${location% *}" -a "$location" != "${location%/}" ]; then
				# no spaces, and trailing '/', append gzfile
				source="${location}${gzfile}"
			else
				source="$location"
			fi
			output="$output\t$source"
		fi

		$ECHO_E "$output"
	done
done