#!/bin/bash

set -e
HM=`pwd`
SD="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
CD=postgresql.chk
TD=/tmp/postgresql.chk

# Internal functions
###############################################################################
compareXhtml() {
    # Compare texts as html's differ in id's and not significant white-space characters
    # Convert html to text in the same directory for inner links to be the same
    [ -d $TD/xhtml ] && rm -rf $TD/xhtml
    cp -R $1 $TD/xhtml
    [ -d $1-text ] && rm -rf $1-text
    mkdir $1-text
    for f in $TD/xhtml/*.html; do fn=`basename $f`; lynx $f --dump >$1-text/$fn; done
    # remove random generated id
    for f in $1-text/*.html; do perl -p -i -e 's/(\.html#(ftn\.)?id)[a-z][0-9]+/$1/g' $f; done

    rm -rf $TD/xhtml
    cp -R $2 $TD/xhtml
    [ -d $2-text ] && rm -rf $2-text
    mkdir $2-text
    for f in $TD/xhtml/*.html; do fn=`basename $f`; lynx $f --dump >$2-text/$fn; done
    # remove random generated id
    for f in $2-text/*.html; do perl -p -i -e 's/(\.html#(ftn\.)?id)[a-z][0-9]+/$1/g' $f; done

    diff -u -b -r $1-text $2-text
}

###############################################################################
rm -rf $CD
rm -rf $TD
mkdir $TD
# this will create ./postgresql.chk/
git clone git://git.postgresql.org/git/postgresql.git $CD
# cp -R postgresql.git $CD
cd $CD
./configure --enable-nls --without-readline --without-zlib

cd doc/src/sgml
time make xslthtml # Slow
cp -R html $TD/xhtml-sgml0
rm -rf html xslthtml-stamp
###############################################################################

# Get and apply XSLT performance patch (https://commitfest.postgresql.org/10/619/)
# wget https://www.postgresql.org/message-id/attachment/44037/xslt-speedup.patch -O - 2>/dev/null | patch
wget https://www.postgresql.org/message-id/attachment/44497/0001-doc-Speed-up-XSLT-builds.patch -O - 2>/dev/null | patch

time make xslthtml # Fast
cp -R html $TD/xhtml-sgml1
rm -rf html xslthtml-stamp
###############################################################################

compareXhtml $TD/xhtml-sgml0 $TD/xhtml-sgml1

echo 'OK'
