#!/bin/sh
# --- SDE-COPYRIGHT-NOTE-BEGIN ---
# This copyright note is auto-generated by ./scripts/Create-CopyPatch.
# 
# Filename: bin/sde-parse-md5
# 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

parse_usage() {
	local progname=${0##*/}
	cat <<EOT
Usage:	$progname [--location <location>] <url>
EOT
}

shortopts='L:'
longopts='location:'
options=$( getopt -o "$shortopts" -l "$longopts" -- "$@" )
if [ $? -ne 0 ]; then
	parse_usage
	exit -1
fi

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

forced_location=

while [ $# -gt 0 ]; do
	case "$1" in
		-L|--location)
			forced_location="$2"; shift ;;

		--)	shift; break ;;
		*)	echo_abort 1 "Unknown argument '$1', aborting."
	esac
	shift
done

# process the urls
#
for md5; do
	# where are these files?
	if [ -n "$forced_location" ]; then
		location="$forced_location"
	else
		location="${md5%/*}"
	fi

	curl "$md5" | while read md5sum file; do
		pkg=$( echo "$file" | sed -e 's,-[0-9].*,,' | tr [A-Z] [a-z] )
		if [ -z "$pkg" ]; then
			echo_error "Failed to detect package name for '$file'."
			continue
		fi

		case "$pkg" in
			exo)	
				pkg=lib${pkg}	;;
			gtk-xfce-engine)
				pkg=${pkg}2	;;
			libxml2)
				pkg=${pkg%2}	;;
			libart_lgpl)
				pkg=${pkg}23	;;
			gtk-doc)
				pkg=gtkdoc	;;
			terminal)
				pkg=xfce4-terminal	;;
			mono/gtk-sharp)
				pkg=gtk-sharp2	;;
			kde-i18n/*|c++/*|java/*|python/*)
				pkg=${pkg#*/}
		esac

		confdir=$( ls -1d $SDEROOT/package/*/$pkg 2> /dev/null || true )
		if [ -z "$confdir" -o ! -f "$confdir/$pkg.desc" ]; then
			echo_error "Failed to detect package name for '$file' ($pkg)."
			continue
		fi

		ver=$( echo "$file" | sed -n -e 's,.*-\([0-9].*\)\.tar\.bz2,\1,p' )
		if [ -z "$ver" ]; then
			echo_error "Failed to detect new version for $pkg ($file)."
			continue
		fi

		echo "$pkg	$ver	$location/$file"
	done
done