#!/bin/sh -e

undivert_man() {
  DSECTION=${2:-8}
  for locale in '' fr/; do
    dpkg-divert --remove --rename --package module-init-tools --divert \
      /usr/share/man/${locale}man$DSECTION/$1.modutils.$DSECTION.gz \
      /usr/share/man/${locale}man$DSECTION/$1.$DSECTION.gz > /dev/null
  done
}

rm_conffile_md5() {
  local file=$1
  local md5=$2
  if [ -f $file ] && echo "$md5  $file" | md5sum -c 2> /dev/null; then
    rm $file
  fi
}

rm_conffile() {
  mv_conffile "$1" "$1.dpkg-bak"
}

mv_conffile() {
  local package='module-init-tools'
  local name="$1"
  local newname="$2"

  [ -e "$name" ] || return 0

  local md5="$(md5sum $name | sed -e 's/ .*//')"
  oldmd5="$(dpkg-query -W -f='${Conffiles}' $package | \
    sed -n -e "\' $name ' { s/ obsolete$//; s/.* //; p }")"

  if [ "$md5" = "$oldmd5" ]; then
    rm -f "$name"
  else
    mv "$name" "$newname"
  fi
}

upgrade_quirks() {
  # $2 is non-empty when installing from the "config-files" state
  [ "$2" ] || return 0

  if dpkg --compare-versions $2 lt 3.10-3; then
  if dpkg --compare-versions $2 lt 3.1-pre11-1; then
  if dpkg --compare-versions $2 lt 3.2-pre9-4; then
  if dpkg --compare-versions $2 lt 3.1-pre2-1; then

  echo 'Upgrading from packages older than 3.1-pre2-1 is not supported.'
  echo 'Please purge module-init-tools before installing this package.'
  exit 1

  fi # lt 3.1-pre2-1

  rm -f /usr/share/man/man8/kallsyms.8.gz /usr/share/man/man8/ksyms.8.gz
  for cmd in kallsyms ksyms; do
    undivert_man $cmd
  done

  fi # lt 3.2-pre9-4

  # remove an obsolete conffile, which was replaced by .../x86_64
  if [ "$(dpkg --print-architecture)" = amd64 ]; then
    rm_conffile_md5 /etc/modprobe.d/arch/i386 688ef8c36b20113c46ec631e6c9effd4
  fi

  fi # lt 3.1-pre11-1

  for file in i386 x86_64 mips s390 parisc sparc powerpc.apus \
       powerpc.generic powerpc.pmac m68k.amiga m68k.atari m68k.generic; do
    rm_conffile /etc/modprobe.d/arch/$file
  done
  rmdir /etc/modprobe.d/arch/ 2> /dev/null || true
  if [ -L /etc/modprobe.d/arch-aliases \
      -a ! -e /etc/modprobe.d/arch-aliases ]; then
    rm /etc/modprobe.d/arch-aliases
  fi

  mv_conffile /etc/modprobe.d/aliases /etc/modprobe.d/aliases.conf

  fi # lt 3.10-3
}

case "$1" in
    install|upgrade)

    upgrade_quirks "$@"
    ;;

    abort-upgrade)
    ;;

    *)
    echo "$0 called with unknown argument '$1'" >&2
    exit 1
    ;;
esac



exit 0
