#!/bin/bash


if [ $# != 2 ] ; then
    echo "Usage: $0 ext-name pkg-name" >&2
    echo "   or: $0 ext-name -list   (to list available packages)" >&2 
    exit 1
fi

ext=$1
pkg=$2


if [ $pkg != "-list" ] ; then
    svn export https://svn.greenstone.org/main/trunk/gs3-extensions/$ext/$pkg
    exit 0
fi

# else we want to list available binaries
if [ "x$WGETRC" != "x" ] ; then

    wgetrc_dir=${WGETRC%/*}

    which_wget=`which wget`
    wget_dir=${which_wget%/*}

    if [ $wgetrc_dir != $wget_dir ] ; then
	echo "+--------" >&2
	echo "+ Located wget is not the Greenstone one" >&2
	echo "+ Temporarily setting:"                   >&2
	echo "+     WGETRC=$WGETRC"                     >&2
	echo "+ to be empty"                            >&2
	echo "+--------" >&2
	export WGETRC=
    fi
fi

command -v wget >/dev/null
wget_status=$?

command -v curl >/dev/null
curl_status=$?

if [ $wget_status = 0 ] ; then
  wget --no-check-certificate -q -O - https://svn.greenstone.org/main/trunk/gs3-extensions/$ext/ | \
    grep '<li>' | \
    sed 's/^.*href="\(.*\)".*$/  \1/' |
    grep -v '\.\.' |
    grep -v 'source'
#     tr '\n' ' '    

elif [ $curl_status = 0 ] ; then
  curl -s https://svn.greenstone.org/main/trunk/gs3-extensions/$ext/ | \
    grep '<li>' | \
    sed 's/^.*href="\(.*\)".*$/  \1/' |
    grep -v '\.\.' |
    grep -v 'source'
  #     tr '\n' ' '
  
else
    echo "Error: Failed to find either 'wget' or 'curl' to download list of available packages from Greenstone svn server for extension $ext" >&2
    exit 1
fi


