#!/bin/sh
# Add or remove the himmelblau NSS service in the passwd, group, shadow, and
# initgroups databases of nsswitch.conf, idempotently.
set -eu

action="${1:-}"
case "$action" in
  add | remove) ;;
  *)
    echo "usage: ${0##*/} <add|remove>" >&2
    exit 2
    ;;
esac

conf="${DPKG_ROOT:-}/etc/nsswitch.conf"
usr_conf="${DPKG_ROOT:-}/usr/etc/nsswitch.conf"

if [ "$action" = add ] && [ ! -f "$conf" ] && [ -f "$usr_conf" ]; then
  cp "$usr_conf" "$conf"
fi
[ -f "$conf" ] || exit 0

tmp="$(mktemp "${conf}.himmelblau.XXXXXX")"
trap 'rm -f "$tmp"' EXIT HUP INT TERM

awk -v action="$action" '
  function target(f) {
    return f == "passwd:" || f == "group:" || f == "shadow:" || f == "initgroups:"
  }
  target($1) {
    h = index($0, "#")
    if (h > 0) { code = substr($0, 1, h - 1); comment = substr($0, h) }
    else       { code = $0;                   comment = "" }

    present = 0
    n = split(code, f, /[[:blank:]]+/)
    for (i = 1; i <= n; i++) if (f[i] == "himmelblau") present = 1

    if (action == "add") {
      if (present) { print; next }
      sub(/[[:blank:]]+$/, "", code)
      if (comment == "") print code " himmelblau"
      else               print code " himmelblau " comment
      next
    }

    if (!present) { print; next }
    while (match(code, /[[:blank:]]+himmelblau([[:blank:]]|$)/)) {
      cut = RLENGTH
      if (substr(code, RSTART + RLENGTH - 1, 1) ~ /[[:blank:]]/) cut = RLENGTH - 1
      code = substr(code, 1, RSTART - 1) substr(code, RSTART + cut)
    }
    if (comment == "") { print code; next }
    sub(/[[:blank:]]+$/, "", code)
    print code " " comment
    next
  }
  { print }
' "$conf" > "$tmp"

chmod --reference="$conf" "$tmp" 2>/dev/null || chmod 0644 "$tmp"
chown --reference="$conf" "$tmp" 2>/dev/null || true
mv "$tmp" "$conf"
trap - EXIT HUP INT TERM
