#!/bin/sh
#
# xmlrpc_results - parse an XML-RPS result and turn it back into xmlrpc args
#
# This makes use of xsltproc, which on FreeBSD is available in
# /usr/ports/textproc/libxslt.
#
# Please don't laugh at the XSLT stylesheet, it's my first ever.

tab='	'
dollar='$'

stylesheet=/tmp/xrss.$$
rm -f $stylesheet
cat > $stylesheet << EOF
<?xml version="1.0" encoding="ISO-8859-1"?>

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>

<xsl:template match="/">
<xsl:apply-templates/>
</xsl:template>

<xsl:template match="value/array">[<xsl:apply-templates/>]</xsl:template>
<xsl:template match="value/struct">{<xsl:apply-templates/>}</xsl:template>
<xsl:template match="member/name"><xsl:value-of select="."/></xsl:template>
<xsl:template match="value/int">-i$tab<xsl:value-of select="."/></xsl:template>
<xsl:template match="value/i4">-i$tab<xsl:value-of select="."/></xsl:template>
<xsl:template match="value/boolean">-b$tab<xsl:value-of select="."/></xsl:template>
<xsl:template match="value/string">-s$tab<xsl:value-of select="."/></xsl:template>
<xsl:template match="value/double">-d$tab<xsl:value-of select="."/></xsl:template>
<xsl:template match="value/dateTime.iso8601">-t$tab<xsl:value-of select="."/></xsl:template>

</xsl:stylesheet>
EOF

if [ $# -eq 0 ] ; then
    set x - ; shift
fi

(
    xsltproc $stylesheet "$@" |
      sed -e "s/^[ $tab]*//" -e "s/[ $tab]*$dollar//" |
      egrep -v '^$' |
      tr '\n' "$tab"
    echo
) |
  sed -e "s/$tab$dollar//"

rm -f $stylesheet
