#!/bin/sh

#### Automatic pdf doc generation from xschem html docs
#### Stefan Schippers, 20211014

tmpdir=__tmp__

#### get list of html files from top level file, preserve order.
get_html_list () {
  echo -n $(grep  '<li>.*href' $root_file \
     | grep -v '/video_tutorials/' \
     | sed 's/^.*href *= *"//' \
     | sed 's/" *>.*//')
}

#### from top index page create pdf doc with internal links
#### 1st parameter is the top page, 2nd parameter is output pdf file.
#### This works specifically for xschem documentation!
#### will not work on generic html docs.
generate_pdf () {
  local root_file output_file
  root_file=$1
  output_file=$2

  #### copy all docs in temporary directory since we must resize images.
  mkdir -p $tmpdir
  cp $(dirname $root_file)/*.html $(dirname $root_file)/*.png $tmpdir
  cd $tmpdir
  #### transform local urls to video tutorial videos to sourceforge hosted videos.
  sed -i '/href *= *"video_tutorials\//s/="/="https:\/\/xschem.sourceforge.io\/stefan\/xschem_man\//' $(basename $root_file)
  
  #### resize images since htmldoc does not fit images in pdf pages at all.
  sed -i '/<img/s/<img /<img width="640" /' *.html
  
  #### generate pdf from list of html files.
  htmldoc --top 10mm --bottom 10mm --right 10mm --left 10mm --webpage --linkcolor blue \
    --footer ..1 --header ..h -t pdf -f ../$output_file $root_file $(get_html_list) 
  cd ..
  #### cleanup
  rm -rf $tmpdir
}

# check for htmldoc else return error exit status
if ! [ -x "$(command -v htmldoc)" ]; then
    echo "htmldoc could not be found"
    return 1
fi

#### generate pdf doc
generate_pdf xschem_man.html xschem_man.pdf
return 0
