#!/usr/bin/env bash
# =============================================================================
# onx-user-exists (v89) — Linux user existence + uid/gid verify
#
# Cheap, read-only verify step run AFTER onx-user-add in
# AccountProvisioner::provision(). Catches the rare race where user-add
# silently "succeeds" but `id <user>` still fails (NSS cache, sudoers TOCTOU,
# slot exhaustion in /etc/passwd write).
#
# Input (stdin JSON):
#   {"username": "onx_alice"}
#
# Output (stdout JSON):
#   {"username":"onx_alice","exists":true,"uid":10042,"gid":10042,"home":"/home/onx_alice","shell":"/bin/bash"}
#   {"username":"onx_alice","exists":false}
#
# Exit codes:
#   0 — always 0 (caller inspects "exists" field; missing user is not a script error)
#   1 — bad/missing input (username empty or not a string)
#
# Sudoers:
#   apache ALL=(root) NOPASSWD: /usr/local/onoxsoft/bin/onx-user-exists
#
# Deployed to: /usr/local/onoxsoft/bin/onx-user-exists
# =============================================================================

set -euo pipefail

SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
# shellcheck source=_lib/common.sh
source "${SCRIPT_DIR}/_lib/common.sh"

onx_json_input
USERNAME=$(onx_json_field "username")

if [[ -z "${USERNAME}" ]]; then
    onx_die 1 "username required"
fi

# Defensive: lightweight pattern (matches onx-user-add convention).
# Reject anything that could escape the upcoming id/getent invocations.
if ! [[ "${USERNAME}" =~ ^[a-z_][a-z0-9_-]{1,31}$ ]]; then
    onx_die 1 "username has invalid characters (allowed: a-z 0-9 _ -)"
fi

if id "${USERNAME}" >/dev/null 2>&1; then
    UID_VAL=$(id -u "${USERNAME}")
    GID_VAL=$(id -g "${USERNAME}")
    # getent passwd: name:passwd:uid:gid:gecos:home:shell
    PASSWD_LINE=$(getent passwd "${USERNAME}" 2>/dev/null || true)
    HOME_DIR=""
    SHELL_BIN=""
    if [[ -n "${PASSWD_LINE}" ]]; then
        HOME_DIR=$(echo "${PASSWD_LINE}" | awk -F: '{print $6}')
        SHELL_BIN=$(echo "${PASSWD_LINE}" | awk -F: '{print $7}')
    fi
    printf '{"username":"%s","exists":true,"uid":%d,"gid":%d,"home":"%s","shell":"%s"}\n' \
        "${USERNAME}" "${UID_VAL}" "${GID_VAL}" "${HOME_DIR}" "${SHELL_BIN}"
else
    printf '{"username":"%s","exists":false}\n' "${USERNAME}"
fi

exit 0
