#!/bin/bash

set -e

impna=$1
style_dir=~/ernad/style/$impna
test_fufi=~/tmp/test.xml

if [ ! $impna ]; then
    echo "I need an impna."
    exit;
fi
if [ ! -d $style_dir ]; then
    echo "You gave me a bad impna '$impna'."
    exit;
fi

# there are files with a template match / but no output
function is_it_endpoint() {
    fufi=$1
    if grep -q "<xsl:output " $fufi; then
        return 1
    fi
    if grep -q "<output " $fufi; then
        return 1
    fi
    if grep -q '<include href="output_text.xslt.xml"/>' $fufi; then
        return 1
    fi
    if grep -q '<xsl:include href="output_text.xslt.xml"/>' $fufi; then
        return 1
    fi
    if grep -q '<include href="output_html.xslt.xml"/>' $fufi; then
        return 1
    fi
    if grep -q '<xsl:include href="output_html.xslt.xml"/>' $fufi; then
        return 1
    fi
    if grep -q '<xsl:template match="/">' $fufi; then
        return 1
    fi
    if grep -q '<template match="/">' $fufi; then
        return 1
    fi
    if grep -q '<xsl:include href="output_html.xslt.xml"/>' $fufi; then
        return 1
    fi
    return 0
}

echo "<root/>" > $test_fufi
cd $style_dir
clear
ls $style_dir/*.xslt.xml |sort -R |while read fufi; do
    if is_it_endpoint $fufi; then
        # echo "not end"
        continue
    fi
    #if [ -h $fufi ]; then
    #    continue
    #fi
    echo $fufi
    /usr/bin/xsltproc $fufi $test_fufi > /dev/null
done
