#!/bin/sh
set -e

is_fs() {
  local fs_type
  fs_type="$(stat --file-system --format=%T "$2" 2> /dev/null)"

  if [ "$fs_type" = "$1" ]; then return 0; fi
  return 1
}

is_merged() {
  local directories="/bin /sbin /lib"
  for dir in $directories; do
    [ -e "$dir" ] || continue
    [ "$(readlink -f "$dir")" = "/usr$dir" ] || return 1
  done

  # Avoid an exact match, as the target might vary depending on the tool
  # building the image. For example, systemd-nspawn links /lib64 to
  # /usr/lib/aarch64-linux-gnu on arm64, while on amd64 debootstrap links it to
  # /usr/lib64 and doesn't create it at all on arm64.
  # See: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=1019575
  local arch_directories="/lib64 /lib32 /libo32 /libx32"
  for dir in $arch_directories; do
    [ -e "$dir" ] || continue
    case "$(readlink -f "$dir")" in
        "/usr/lib"*) ;;
        *) return 1;;
    esac
  done

  return 0
}

maybe_convert() {
  # do not try to run the program if the system has already been converted
  if is_merged; then return; fi

  if is_fs nfs / || is_fs nfs /usr; then
    cat << 'END' >&2

Warning: NFS detected, /usr/lib/usrmerge/convert-usrmerge will not be run
automatically. See #842145 for details.

END
    return 1
  fi

  /usr/lib/usrmerge/convert-usrmerge || return $?

  if which update-shells > /dev/null; then
    update-shells
  fi
  /usr/lib/usrmerge/convert-etc-shells || return $?
}

cleanup_biarch_dirs() {
  dpkg --compare-versions "$2" lt "36~" || return 0

  # bootstrapping or earlier conversions may have created empty biarch
  # directories and links. glibc 2.35-4 or later will create them if needed,
  # so clean up the unused (and unowned) ones
  local arch_directories="/lib64 /lib32 /libo32 /libx32"
  for dir in $arch_directories; do
    [ -e "$dir" ] || continue
    if ! dpkg-query -S $dir >/dev/null 2>&1; then
      rm -v $dir
      if [ -e /usr$dir ] && ! dpkg-query -S /usr$dir >/dev/null 2>&1 ; then
        rmdir --ignore-fail-on-non-empty -v /usr$dir
      fi
    fi
  done
}

case "$1" in
    configure)
	# Skip the conversion for buildds.
	# Note that such systems will be *UNSUPPORTED* in the future.
	if [ -e /etc/unsupported-skip-usrmerge-conversion ] && \
	    grep -q 'this system will not be supported in the future' \
	      /etc/unsupported-skip-usrmerge-conversion; then
	  echo "W: /etc/unsupported-skip-usrmerge-conversion exists." >&2
	else
	  maybe_convert "$@" || { echo "E: usrmerge failed." >&2; exit 1; }
	  cleanup_biarch_dirs
	fi
    ;;
esac

# Automatically added by dh_installdeb/13.11.4
dpkg-maintscript-helper rm_conffile /etc/dpkg/dpkg.cfg.d/usrmerge 19\~ usrmerge -- "$@"
# End automatically added section


