#! /usr/bin/env bash

# Shift a section in the ODB manual. This is normally necessary when
# you need to insert new content at a specific place. For example,
# you may have sections 10.1 10.2, and 10.3 and you need to insert a
# new 10.2 section and shift the old 10.2 to 10.3 and the old 10.3
# to 10.4. To accomplish this, performs the following steps:
#
# 1. Commit or stage existing changes to the manual.
# 2. Run 'shift-section.sh -p 10 -l 3 -h 3 manual.xhtml' Note that
#    you should always start from the last section you need to shift
#    and work your way backwards.
# 3. Review the changes with diff or gitk, make sure the script didn't
#    mess up. Note that the script is KNOWN TO MESS UP sometimes so this
#    step if not optional. If everything is good, stage the changes and
#    repeat steps 2-3 for the next section.
#
# If you need to shift a lot of leaf sections (i.e., sections that do
# not have sub-sections, then you can try to do the whole thing in one
# step. However, catching script errors will be harder. For example:
#
# shift-section.sh -p 10.4 -l 8 -h 23 manual.xhtml
#
# -p <section-prefix>
# -l <low-bound>
# -h <high-bound>
#

function error ()
{
  echo "$*" 1>&2
}

prefix=
low=
high=
usage="$0 -p <section-prefix> -l <low-bound> -h <high-bound> manual.xhtml"

while [ $# -gt 0 ]; do
  case $1 in
    -p)
      shift
      prefix="$1"
      shift
      ;;
    -l)
      shift
      low="$1"
      shift
      ;;
    -h)
      shift
      high="$1"
      shift
      ;;
    -*)
      error "unknown option: $1"
      exit 1
      ;;
    *)
      break
      ;;
  esac
done

if [ "$low" = "" ]; then
  error "low bound is not specified"
  error $usage
  exit 1
fi

if [ "$high" = "" ]; then
  error "high bound is not specified"
  error $usage
  exit 1
fi

if [ "$1" = "" ]; then
  error "document is not specified"
  error $usage
  exit 1
fi

for (( i=$high; i>=$low; i-- )); do

  if [ "$prefix" != "" ]; then
    old="$prefix."
    new="$prefix."
  fi

  old="$old$i"
  new="$new$((i+1))"

  # Escape periods in the old section names.
  #
  eold=`echo $old | sed -e 's/\./\\\\./g'`

  #echo "$eold"
  #echo "$new"

  sed -e 's/\([># "]\)'"$eold/\1$new/g" $1 >$1.shifted

  if [ "$?" != 0 ]; then
    rm -f $1.shifted
    exit 1
  fi

  cmp -s $1 $1.shifted

  if [ "$?" != 0 ]; then
    mv $1.shifted $1
  else
    rm $1.shifted
    error "document unchanged on step $old -> $new"
    exit 1
  fi

done