#!/bin/bash

set -eu

if [ $# -ne 1 ]; then
  echo 'Run this script with one arg: top level install directory' 1>&2
  exit 1
fi

src="$(cd "$(dirname "$0")" && pwd)"
dst="$1"

# makeindices.pl seems to ignore locale, but just in case:
export LC_COLLATE=C
export LC_ALL=C

pushd html >/dev/null
# update html/REFERENCES.html
#./makereference

# update INDEX.html, FUNCTIONS.html, whatis
# (to simplify build, two files are hardcoded in the makeindices.pl script:
#  ../share/ccp4i/help/roadmaps/index.html and
#  ../examples/tutorial/html/index.html)
#./makeindices.pl *.html pxmaths/*.html C_library/*.html

dups=$(uniq -d INDEX.html)
if [ -n "$dups" ]; then
    echo "Duplicates in INDEX.html:"
    echo "$dups"
fi
popd >/dev/null

mkdir -p "$dst"/html
cp -af html/* "$dst"/html

if ! lynx -version >/dev/null; then
  echo 'no lynx - "man pages" will not be generated/updated.'
  exit 0 # it's fine, we don't do man pages on Windows
fi

cd "$dst"
mkdir -p share/man/cat1
for h in html/*.html; do
  # Not sure which html pages should have corresponding man pages.
  # Let it be all supported programs + pages that look like man-page
  if grep '::Supported::\|SYNOPSIS' $h > /dev/null; then
    lynx -dump -nolist -width=71 "$h" >share/man/cat1/"$(basename "$h" .html)".1
  fi
done

# "whatis" is for "man -k"/apropos
mv -f html/whatis share/man/

