#!@l_prefix@/bin/bash

PREFIX=${PREFIX-@l_prefix@}
DIR=$PREFIX/share/sgml
MASTER=$DIR/catalog.xml
MK=$PREFIX/libexec/sgml/mkcatalog
C2X=$PREFIX/libexec/sgml/catalog2xml

init () {
    p=()
    s=()
    u=()
    P=()
    S=()
    U=()
    X=0
}

setup () {
    if test ! -s $MASTER
    then
        cat > $MASTER <<'EOFEOF'
<?xml version="1.0"?>
<!DOCTYPE catalog PUBLIC "-//OASIS//DTD Entity Resolution XML Catalog V1.0//EN" "http://www.oasis-open.org/committees/entity/release/1.0/catalog.dtd">
<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog">
</catalog>
EOFEOF
        ls -l $MASTER
    fi
}

del () {
    name="$1"

    while read line
    do
        case "$line" in
        "<!-- CATALOG $name -->"*)
            ;;
        *)
            echo $line
            ;;
        esac
    done < $MASTER > $MASTER.tmp && \
    cp $MASTER.tmp $MASTER && \
    rm -f $MASTER.tmp
}

ins () {
    name="$1" ; shift
    tag="$1" ; shift
    att1="$1" ; shift
    att2="$1" ; shift
    val2="$1" ; shift

    while read line
    do
        case "$line" in
        "</catalog>")
            for val1 in "$@"
            do
                echo '<!-- CATALOG' $name '--><'$tag $att1='"'$val1'"' $att2='"'$val2'"/>'
            done
            echo $line
            ;;
        *)
            echo $line
            ;;
        esac
    done < $MASTER > $MASTER.tmp && \
    cp $MASTER.tmp $MASTER && \
    rm -f $MASTER.tmp
}

install () {
    name=$1
    cat="file://$DIR/$name/catalog.xml"
    pre="file://$DIR/$name"

    $MK -q install $name

    if test $X -gt 0
    then
        $C2X $DIR/$name/catalog > $DIR/$name/catalog.xml
    fi

    del $name

    ins $name delegatePublic publicIdStartString catalog $cat "${p[@]}"
    ins $name delegateSystem systemIdStartString catalog $cat "${s[@]}"
    ins $name delegateURI    uriStartString      catalog $cat "${u[@]}"

    ins $name rewritePublic publicIdStartString rewritePrefix $pre "${P[@]}"
    ins $name rewriteSystem systemIdStartString rewritePrefix $pre "${S[@]}"
    ins $name rewriteURI    uriStartString      rewritePrefix $pre "${U[@]}"
}

deinstall () {
    name=$1

    $MK -q deinstall $name

    if test $X -gt 0
    then
        rm -f $DIR/$name/catalog.xml
    fi

    del $name
}

init
setup

while test $# -gt 0
do
    i="$1" ; shift
    case "$i" in
    -p)
        p=("${p[@]}" "$1") ; shift
        ;;
    -s)
        s=("${s[@]}" "$1") ; shift
        ;;
    -u)
        u=("${u[@]}" "$1") ; shift
        ;;
    -P)
        P=("${P[@]}" "$1") ; shift
        ;;
    -S)
        S=("${S[@]}" "$1") ; shift
        ;;
    -U)
        U=("${U[@]}" "$1") ; shift
        ;;
    -i)
        name="$1" ; shift
        install "$name"
        init
        ;;
    -x)
        X=1
        ;;
    -d)
        name="$1" ; shift
        deinstall "$name"
        init
        ;;
    esac
done
