#! /bin/sh


set -eu

# 3.160-ONLY: this function exists only to repair the damage of a bug in
# adduser 3.160, which was only in unstable for a few days. It can be
# removed, together with reset_3_160_stale_id_counters in AdduserCommon.pm
# and its test, as soon as an upgrade from 3.160 is no longer possible.
#
# adduser 3.160 recorded ids in its id counter that it had taken over from
# the gid of the --ingroup group instead of drawing them from the counter.
# A group with gid 999 thus moved the counter of the system range to the
# end of the range, and adduser --system refused to work from then on.
# Reset counters that sit at the end of their range.
fix_3_160_id_counters() {
  OLDVERSION="${1:-}"
  # the id counter was introduced with 3.160, the bug fixed in 3.161
  if [ -z "${OLDVERSION}" ] \
    || dpkg --compare-versions "${OLDVERSION}" lt 3.160 \
    || dpkg --compare-versions "${OLDVERSION}" ge 3.161; then
    return 0
  fi
  [ -f /var/lib/adduser/state ] || return 0
  [ -f /etc/adduser.conf ] || return 0
  # failing to repair the counter must not break the upgrade
  perl -MDebian::AdduserLogging -MDebian::AdduserCommon -e '
    set_msglevel("warn", "info", "info");
    my %config = read_config("/etc/adduser.conf");
    reset_3_160_stale_id_counters(\%config);
  ' || printf "adduser: could not check the id counters in /var/lib/adduser/state\n" >&2
}

case $1 in
  configure)
    # 3.160-ONLY, see above
    fix_3_160_id_counters "${2:-}"
    ;;
esac

set +eu

#DEBHELPER#
