#!/bin/bash

## Copyright (C) 2012 - 2025 ENCRYPTED SUPPORT LLC <adrelanos@whonix.org>
## See the file COPYING for copying conditions.

set -o errexit
set -o nounset
set -o errtrace
set -o pipefail

if test -r /etc/adduser.conf; then
  adduser_conf_file="$(cat -- /etc/adduser.conf)"

  ## TODO: Consider multiple matches of FIRST_UID and LAST_UID. Match only last?

  first_uid="$(
    grep 'FIRST_UID' <<<"${adduser_conf_file}" | grep -v -- '^\s*#' \
      | cut -d'=' -f2 | sed 's/^[[:space:]]*//'
  )" || true

  if [[ "$first_uid" = *[!0-9]* ]]; then
    echo "$0: ERROR: FIRST_UID in file /etc/adduser.conf is not strictly numeric!" >&2
    exit 1
  fi

  last_uid="$(
    grep 'LAST_UID' <<<"${adduser_conf_file}" | grep -v -- '^\s*#' \
      | cut -d'=' -f2 | sed 's/^[[:space:]]*//'
  )" || true

  if [[ "$last_uid" = *[!0-9]* ]]; then
    echo "$0: ERROR: LAST_UID in file /etc/adduser.conf is not strictly numeric!" >&2
    exit 1
  fi
fi

if [ -z "${first_uid:-}" ]; then
  first_uid=1000
fi
if [ -z "${last_uid:-}" ]; then
  last_uid=59999
fi

if ! test -r /etc/passwd; then
  echo "$0: ERROR: file /etc/passwd is not readable!" >&2
  exit 1
fi

while read -r user_entry; do
   current_uid="$(cut -d':' -f3 <<< "${user_entry}")"
   if [ "${current_uid}" -ge "${first_uid}" ] \
      && [ "${current_uid}" -le "${last_uid}" ]; then
      cut -d':' -f1 <<< "${user_entry}"
   elif [ "${current_uid}" = '0' ]; then
      ## Include the root user in the list.
      cut -d':' -f1 <<< "${user_entry}"
   fi
done < /etc/passwd
