#! /bin/bash -e

# The script takes two filenames as arguments: the *.toc and *.llg files
# LaTeX has generated, the latter on special instructions in the book's source.
# From the *.llg, it reads the page numbers of the book's table of contents,
# bibliography and index, writing to stdout an updated *.toc file with these
# entries added.

[[ $# == 2 ]] || false

OLDTOC=$1
PAGE_NO=$2

PROGDIR=$( dirname $0 )
TEXDIR=$PROGDIR/../tex

function page_no {
  sed -ne \
  "s/^[[:space:]]*$1[[:space:]]\\+\\([^[:space:]]\\+\\)[[:space:]]*\$/\\1/p;T;q" \
  $PAGE_NO
}

function toc_line {
  echo "\\contentsline {chapter}{$1}{$( page_no $1 )}"
}

toc_line Contents
cat $OLDTOC
toc_line Bibliography
toc_line Index

