#!/bin/sh

set -e
set -u

mkdir -p otherdocs/sasmodels/build/lib otherdocs/bumps

SASDOC=/usr/share/doc/python-sasmodels/html
cp -r $SASDOC/_sources otherdocs/sasmodels/doc
cp -r $SASDOC/_images otherdocs/sasmodels/doc/images

ln -s /usr/lib/python2.7/dist-packages/sasmodels otherdocs/sasmodels/build/lib/

BUMPDOC=/usr/share/doc/python-bumps/html
cp -r $BUMPDOC/_sources otherdocs/bumps/doc
cp -r $BUMPDOC/_images otherdocs/bumps/doc/images

# fix up the extensions
find otherdocs -name \*.rst.txt -exec \
    file-rename 's/.rst.txt/.rst/' {} +

# horrible hack to find the missing images and copy them back in

# first make sure all figures are on a single rst line
(
    cd otherdocs/sasmodels/doc/guide/magnetism/
    awk '/\.\. figure::$/{printf $0; next}; {print}' magnetism.rst > magnetism.rst.tmp
    mv magnetism.rst.tmp magnetism.rst
)

fetchimages() {
    srcdir=$1/doc
    imgcache=$1/doc/images

    for src in $(grep -r -e'\.\. figure::' -e'\.\. image::' -l $srcdir); do
        echo "# Inspecting $src"
        base=$(dirname $src)
        for img in $(sed -rn 's@\.\. (figure|image):: (.*)@\2@p' $src); do
            echo "## Image $img"
            path=$base/$(dirname $img)
            fname=$(basename $img)
            echo "   path=$path fname=$fname"
            mkdir -p $path
            if ! cp $imgcache/$fname $path; then
              echo "ERROR: couldn't find $img in $path"
            fi
        done
    done
}

fetchimages otherdocs/sasmodels
fetchimages otherdocs/bumps
