#!/bin/bash

# This script fixes up various problems with the man pages.

# Create the symlinks for multiple and alternative names when they are
# described in a single man page.

sections="1 3 5 8"
#echo "sections = $sections"

for s in $sections; do
    files=$(grep -rl '^\.SH NAME' debian/tmp/usr/share/man/man$s | \
      grep -v '/netsnmp_')
    #echo "files = $files"

    for f in $files; do
	if [[ ! -f $f ]]; then
	    continue
	fi

	f2=$(basename $f .$s)
	commands=$(sed -e '/^\.SH NAME/,/^\./p' -e d $f | 
	    sed -e '/^\./d' -e 's/,/ /g' -e 's/\\\?-.*$//')
	#echo "$f2 commands = $commands"

	for c in $commands; do
	    c2=$(basename $c)
	    if [[ $c2 != $f2 ]]; then
		#echo ln -sf $f2.$s debian/tmp/usr/share/man/man$s/$c2.$s
		ln -sf $f2.$s debian/tmp/usr/share/man/man$s/$c2.$s
	    fi
	done
    done
done

# Rename the pages to avoid possible conflicts with other packages.

mv debian/tmp/usr/share/man/man3/SNMP.3 debian/tmp/usr/share/man/man3/SNMP.3pm

sections="3 5"
#echo "sections = $sections"

for s in $sections; do
    files=debian/tmp/usr/share/man/man$s/*.$s
    #echo "files = $files"

    for f in $files; do
	if [[ -L $f ]]; then
	    l=$(readlink $f)
	    #echo ln -sf ${l}snmp ${f}snmp
	    ln -sf ${l}snmp ${f}snmp
	    rm -f $f
	else
	    #echo mv $f ${f}snmp
	    sed -e "s/^\(\.TH \"[^\"]*\"\|\.TH [^\"][^ ]*\) *${s}/\1 ${s}snmp/" < $f > ${f}tmp
	    sed -e "s/^\(\.so .*\)${s}$/\1${s}snmp/" < ${f}tmp > ${f}snmp
	    rm -f $f
	    rm -f ${f}tmp
	fi
    done
done
