#!/bin/sh
# --- SDE-COPYRIGHT-NOTE-BEGIN ---
# This copyright note is auto-generated by ./scripts/Create-CopyPatch.
#
# Filename: bin/sde-download-get
# Copyright (C) 2007 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

download_usage() {
	local progname=${0##*/}
	cat <<EOT >&2
Usage:	$progname [-vqd] <target> <source>
EOT
}

shortopts='nqv'
longopts='dry-run,quiet,verbose'
options=$( getopt -o "$shortopts" -l "$longopts" -- "$@" )

if [ $? -ne 0 ]; then
	download_usage
	exit -1
fi

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

dryrun=
verbose=1
target=
source=

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

		-n|--dry-run)
			dryrun="yes" ;;
		-v|--verbose)
			let verbose++ ;;
		-q|--quiet)
			let verbose-- ;;
	esac
	shift
done

# now take the real arguments
if [ $# -lt 2 ]; then
	echo_error "Not enough arguments given."
	download_usage
	exit -1
fi

target="$1"; shift
protocol=${1%%:*}

# debug output
[ $verbose -le 1 ] || echo_info "($protocol) $@"

# find the right handler
if [ -x "$SDEROOT/bin/sde-download-$protocol" ]; then
    handler="$SDEROOT/bin/sde-download-$protocol"
else
    handler=$( grep -l "^#Protocol: $protocol\$" "$SDEROOT/bin"/sde-download-* 2> /dev/null )
fi
handleropt=

[ -x "$handler" ] || echo_abort 2 "$protocol: protocol unhandled"

if [ -n "$dryrun" ]; then
	echo "(${handler##*/}) $source"
elif [ ! -e "$target.lock" ]; then

	# arguments for the handler, reduce the verbosity on one level
	if [ $verbose -gt 2 ]; then
		handleropt="-v"
	elif [ $verbose -lt 0 ]; then
		handleropt="-q"
	fi

	exec "$handler" $handleropt -- "$target" "$@"
fi