#!/bin/sh
#
#  Script to invoke XSLT program that transforms the output from
#  dCache's info service into WLCG Storage Descriptor JSON file.
#
#  This file is intended to be run from cron, generating
#  storage-descriptor output that is written into dCache using an NFS
#  mount.

#  Temporary XML file containing dCache's current configuration.
buildEntitiesFile() # in $1 entity file, $2 catalogue file.
{
    DCACHE_LOG=error bootLoader -q compile -xml > "$1"

    cat > "$2" <<EOF
<?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">
    <public publicId="-//dCache//ENTITIES dCache Properties//EN"
            uri="file://$1"/>
</catalog>
EOF
}

# Load libraries

[ -f /etc/default/dcache ] && . /etc/default/dcache       
[ -f /etc/dcache.env ] && . /etc/dcache.env               

if [ -z "$DCACHE_HOME" ]; then                            
DCACHE_HOME="/usr/share/dcache"                         
fi                                                        
if [ ! -d "$DCACHE_HOME" ]; then                          
echo "$DCACHE_HOME is not a directory"                  
exit 2                                                  
fi                                                        

DCACHE_CLASSPATH=${DCACHE_HOME}/classes/*                 
DCACHE_DEFAULTS=${DCACHE_HOME}/defaults                   
DCACHE_CACHED_CONFIG=/var/lib/dcache/config/cache         
. ${DCACHE_HOME}/lib/loadConfig.sh                        
if [ "$(id -u)" -eq 0                                       -a -f /lib/systemd/system-generators/dcache-generator  -a "$(basename $0)" != "dcache-generator"              -a -f /bin/systemctl ]; then                         
for unit in /run/systemd/generator/dcache@*.service; do 
if [ "$DCACHE_CACHED_CONFIG" -nt "$unit" ]; then      
systemctl daemon-reload                             
break                                               
fi                                                    
done                                                    
fi
. "$(getProperty dcache.paths.share.lib)/utils.sh"

xslt="$(getProperty storage-descriptor.xslt.path)"
output="$(getProperty storage-descriptor.output.path)"
if [ $# -ge 1 ]; then
    infoUrl="$1"
else
    infoUrl="http://${host}:${port}/info"
fi
host="$(getProperty storage-descriptor.http.host)"
port="$(getProperty storage-descriptor.http.port)"

entities=$(mktemp)
catalog=$(mktemp)
trap "rm -f $entities $catalog" EXIT
buildEntitiesFile "$entities" "$catalog"

export XML_CATALOG_FILES="$catalog"
curl -sS "$infoUrl" | \
    xsltproc --xinclude "$xslt" - > "$output"
echo "JSON available at $output"
