#!/bin/sh
# vim: ts=2 et sw=2
# Fix 'spare-manual-page' lintian warnings by moving to section 7x all
# those manual pages from section 1x for which /usr/bin executable do
# not exists.
set -e

# Check if first argument passed to the function is
# the same as one of the other arguments.
argument_exists()
{
  what="$1"
  shift
  for arg in "$@"; do
    [ "$what" != "$arg" ] || return 0
  done
  return 1
}

die()
{
  echo "ERROR in $0: $@" >&2
  exit 1
}

[ -d debian ] || cd ..
[ -d debian ] || cd ..
[ -d debian ] || die "Can't find debian directory"


export LC_ALL=C
readonly dir="$1"

readonly man1dir="$dir/usr/share/man/man1"
readonly man7dir="$dir/usr/share/man/man7"

# Override "$@" with a list of binaries existing in debian/packages.d files
set -- $(sed -nre '/^%(install|links)%/,/^%/{
                     s|^#.*$||; s|\s*$||;
                     s|\*|__INVALID__|g;
                     s|([^/\t ]+)\s+usr/bin/*$|&/\1|;
                     s|^.*\s+||;
                     s|usr/bin/+||p}' debian/packages.d/*.in)
[ "$1" ] || die "Failed to parse packages.d files"


! echo "$@" | grep -q '__INVALID__'  || \
   die "debian/packages.d/*.in contain usr/bin" \
       "entries with '*' in install or links sections"

echo "List of /usr/bin binaries in package.d/*.in files: $@"

[ -d "$man1dir" ] || die "$man1dir does not exists"
mkdir -m 755 -p "$man7dir"

cd "$man1dir"
for file in *.1x; do
  # We install afterstep binary, not AfterStep
  basename="${file%.*}"
  if [ "$basename" = "AfterStep" ] ; then
    echo "Renaming $basename man page to afterstep.1x"
    mv "$file" afterstep.1x
    continue
  fi

  ! argument_exists "$basename" "$@" || continue
  echo "Moving $basename man page from section 1x to 7x"
  sed -i -e '/^\.TH/s| 1x | 7x |g' "$file"
  mv "$file" "$man7dir/$basename.7x"
done
