#!/bin/bash

# Set environment variables and call do-*.sh in sequence

[ -z "$WEBDIR" ] && export WEBDIR=~/www/kdocs
[ -z "$LNXDIR" ] && export LNXDIR=~/linux

# Update mercurial repository
if [ "$1" != "--nonet" ]
then
  "$WEBDIR"/make/do-gethg.sh || exit 1
fi

echo -n "Grab version number..."
export LNXTAG="$(hg tags | head -n 2 | tail -n 1 | awk '{print $1}')"
echo $LNXTAG

echo "Update master index."
"$WEBDIR"/make/do-master.sh || exit 1

echo "Mirror resources"
"$WEBDIR"/make/do-mirror.sh || exit 1

echo Copy readme files from Linux kernel
"$WEBDIR"/make/do-readme.sh || exit 1

echo Convert kconfig to html for all architectures
"$WEBDIR"/make/do-menuconfig.sh || exit 1

echo Install updated Documentation

rm -rf $WEBDIR/Documentation/
cp -a $LNXDIR/hg/Documentation $WEBDIR/Documentation
cd $WEBDIR
for i in make/patches/*.patch
do
  echo $i
  patch -p1 -i $i || exit 1
done
make/docdiridx.py

[ "$1" == "--short" ] && exit 1

echo Build htmldocs and xhtml-nochunks

rm -rf $LNXDIR/temp
cd $LNXDIR/hg
mkdir $LNXDIR/temp
make allnoconfig O=$LNXDIR/temp

# Adjust to use the patched Documentation directory
ln -s $WEBDIR/Documentation $LNXDIR/temp

# I have a dual processor laptop, so overlap work here.  Generate the xml
# first, then have make htmldocs produce split-up versions in the background
# while a script produces nochunks versions in the foreground.
cd $LNXDIR/temp
make -j 2 xmldocs
[ "$1" != "--skimp" ] && make -j 2 htmldocs &
cd Documentation/DocBook
for i in *.xml
do
  echo "Converting $i"
  xmlto xhtml-nochunks $i -o xhtml-nochunks 
done
# Wait for background task to finish before retrieving result
[ "$1" != "--skimp" ] && while [ $(jobs | wc -l) -ne 0 ]
do
  sleep 1
  # Without this next line, bash never notices a change in the number of jobs.
  # Bug noticed in Ubuntu 7.04
  jobs > /dev/null
done
mv xhtml-nochunks/*.html .
rmdir xhtml-nochunks

echo Install htmldocs and update index

rm -f $WEBDIR/htmldocs
ln -s Documentation/DocBook $WEBDIR/htmldocs
cd $WEBDIR/htmldocs
# Work around a bug in xmlto: it puts an incorrect code page into the converted
# html documents, which produces line noise in the output.
find . -name "*.html" | xargs sed -i -e 's/.*ISO-8859-1.*//'
head -n 2 index.html > index2.html
echo "<ul>" >> index2.html
for i in $(ls -p | sed -n 's@/$@@p')
do
  echo "<li>(<a href=\"$i\">chunks</a>) (<a href=\"${i}.html\">nochunks</a>) " >> index2.html
  sed -nr 's@.*<title>(.*)</title>.*@\1@p' ${i}.xml | head -n 1 >> index2.html
  echo "</li>" >> index2.html
done
echo "</ul>" >> index2.html
mv index2.html index.html

# Search for references to RFC documents
"$WEBDIR"/make/findrfc.sh > "$WEBDIR"/rfc-linux.html || exit 1

echo "Done with kdocs"
