#!/usr/bin/env bash
# vim: set ts=3 sts=48 sw=3 cc=76 et fdm=marker: # **** IGNORE ******
get_range() { RANGE= # <-- OUTPUT                  **** THIS   ******
   local rstart rend i arr=( "$@" )  # ported from **** JUNK   ******                        
   for (( i=0 ; i < $# ; i++ )); do  # http://stackoverflow.com   
      (( rstart = arr[i] ))          # /a/2270987/912236          
      rend=$rstart; while (( arr[i+1] - arr[i] == 1 )); do
      (( rend = arr[++i] )); done; (( rstart == rend )) && 
      RANGE+=" $rstart" || RANGE+=" $rstart-$rend"; done; } # }}}

INPUT=${1}  # Take input from command line
# INPUT=jcv_vsm.html
BASE=${INPUT%.html}
OUTPUT="$BASE.pdf"

# Take the cover/copyright notice from the 
# final output document, and insert it before
# each volume.
#
# You can specify other pages from other sources
# here too.
#    eg:  INSERTS=( "cover-a4.pdf" "1" )

INSERTS=( "$OUTPUT" "1-2" )

# Join the chapters up-to a maximum of MAX_SECTION_PAGE_COUNT

MAX_SECTION_PAGE_COUNT=$(( 738 ))

# It takes a while to generate 2,000 pages so 
# for testing and demonstration purposes, we'll
# use a document that has already completed.

SAMPLE_PRINCE_OUTPUT='prince: @@CHAPTERS: chapters=(  "3..592" "1000..1775" )'
SAMPLE_PRINCE_OUTPUT='prince: @@CHAPTERS: chapters=(  "3..16" "17..18" "19..22" "23..-1"  "111..128" "129..146" "147..172" "173..-1" "191..208" "209..218" "219..-1"    "313..-1"  "325..328" "329..334" "335..352" "353..400" "401..405")'


# Else, we could run prince and grab the output
  SAMPLE_PRINCE_OUTPUT=$(
  # false &&
  http_proxy=                                   \
  prince                                        \
   --script jcv-chapters.js                     \
   -s jcv-chapters.css                          \
   $INPUT                                       \
   -vo $OUTPUT                                  \
   2>&1                                         \
   | tee /dev/stderr                            \
   | grep 'prince: @@CHAPTERS'                  
)

# Extract the chapter information from the output
# string.

chapter_vardef=${SAMPLE_PRINCE_OUTPUT##*@@CHAPTERS: chapters=}
declare -a PRINCE_CHAPTER_LIST="$chapter_vardef"

# Now we're going to expand out each chapter 
# into individual pages, then copy those pages
# to a numbered PDF.  Yes, we could have
# just used a range, but this way is cooler.
# e.g. we can easily count how many pages there
# are in a group, and do things with odd/even
# CHAPTERS, or factors of 4 or 8 (for pageup's)

# Iterate through all the CHAPTERS, and join 
# them into volumes.

VOLUME_NUMBER=1
SECTION_PAGE_COUNT=0
SECTION_PAGE_LIST="${INSERTS[@]} "

for key in "${!PRINCE_CHAPTER_LIST[@]}"
do
   chapter=${PRINCE_CHAPTER_LIST[$key]}
   
   # Expand the chapter range into page numbers
   declare -a 'CHAPTER_PAGE_LIST=({'"$chapter"'})'

   # Work out total page count
   CHAPTER_PAGE_COUNT=${#CHAPTER_PAGE_LIST[@]}
      
   # Compress list of pages into a range (don't laugh)
   get_range "${CHAPTER_PAGE_LIST[@]}" # put into $RANGE
   if (( CHAPTER_PAGE_COUNT + SECTION_PAGE_COUNT 
      >= MAX_SECTION_PAGE_COUNT ))
   then  # have we exceed the maximum page length? if so, output
         # everything until now. zero pad volume number.
      printf -v part %02d $VOLUME_NUMBER

      echo "Making part $part with $SECTION_PAGE_COUNT pages"
      pdfjam $RANGE --outfile "$BASE-part$VOLUME_NUMBER.pdf" 

      (( VOLUME_NUMBER ++ ))
      (( SECTION_PAGE_COUNT = CHAPTER_PAGE_COUNT ))
      SECTION_PAGE_LIST="${INSERTS[@]} $OUTPUT $RANGE "
   else
      SECTION_PAGE_LIST+="$OUTPUT $RANGE "
      (( SECTION_PAGE_COUNT += CHAPTER_PAGE_COUNT ))
   fi
done

# We have to deal with the pages left over yet!

printf -v part %02d $VOLUME_NUMBER 

echo "Making part $part with $SECTION_PAGE_COUNT pages"
pdfjam $SECTION_PAGE_LIST --outfile "$BASE-part$VOLUME_NUMBER.pdf" 

echo Done.
