#!/usr/bin/env bash
# =============================================================================
# onx-ftp-pure-user-list — Pure-FTPd PureDB virtual user listesi
#
# v88 Agent 3 — Default FTP User System.
# pure-pw list çıktısı + her user için pure-pw show ile detay birleştirir.
#
# Input (stdin JSON):
#   {
#     "filter":      "onx_*",          -- glob (shell pattern), default "*"
#     "passwd_path": "/etc/pure-ftpd/pureftpd.passwd",
#     "with_quota":  true              -- false ise sadece username+home+uid
#   }
#
# Output (stdout JSON):
#   {
#     "ok": true,
#     "count": 3,
#     "users": [
#       {"username":"onx_xxx","homedir":"/home/users/onx_xxx",
#        "uid":12345,"gid":12345,"quota_files":1000,"quota_size_mb":500},
#       ...
#     ]
#   }
#
# Exit codes: 0=ok 1=invalid-input 2=preflight 3=exec-fail
# =============================================================================

set -euo pipefail

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

require_root
command -v jq      >/dev/null 2>&1 || onx_die 2 "jq gerekli"
command -v pure-pw >/dev/null 2>&1 || onx_die 2 "pure-pw bulunamadi"

INPUT="$(cat 2>/dev/null || true)"
[[ -z "${INPUT}" ]] && INPUT='{}'
echo "${INPUT}" | jq -e 'type == "object"' >/dev/null 2>&1 \
    || onx_die 1 "stdin gecersiz JSON nesnesi"

FILTER=$(onx_json_get      "${INPUT}" "filter"      "*")
PASSWD=$(onx_json_get      "${INPUT}" "passwd_path" "/etc/pure-ftpd/pureftpd.passwd")
WITH_QUOTA=$(onx_json_get_bool "${INPUT}" "with_quota" "true")

[[ -f "${PASSWD}" ]] || onx_die 2 "pureftpd.passwd bulunamadi (${PASSWD})"

# pure-pw list — her satir: username\thome
# Filter shell glob; pure-pw'in built-in filter'i yok, manuel grep
ALL_USERS="$(pure-pw list -f "${PASSWD}" 2>/dev/null || true)"

# Glob → grep regex çevirimi (basit: * → .*, ? → .)
GREP_PATTERN="^$(printf '%s' "${FILTER}" | sed 's/[.[\(*+?^$|]/\\&/g; s/\\\*/.*/g; s/\\?/./g')$"

USERS_JSON='[]'
COUNT=0
while IFS= read -r LINE; do
    [[ -z "${LINE}" ]] && continue
    UNAME="$(printf '%s' "${LINE}" | awk '{print $1}')"
    [[ -z "${UNAME}" ]] && continue
    # Filter match
    if ! printf '%s' "${UNAME}" | grep -qE "${GREP_PATTERN}"; then
        continue
    fi

    HOMEDIR=""; UID_VAL=""; GID_VAL=""; QFILES=""; QSIZE=""
    if [[ "${WITH_QUOTA}" == "true" ]]; then
        SHOW="$(pure-pw show "${UNAME}" -f "${PASSWD}" 2>/dev/null || true)"
        # pure-pw show formati: "Login    : <user>" satirlari
        HOMEDIR="$(printf '%s\n' "${SHOW}" | awk -F': *' '/^Directory[ \t]*:/ {print $2; exit}')"
        UID_VAL="$(printf '%s\n'  "${SHOW}" | awk -F': *' '/^UID[ \t]*:/ {print $2; exit}')"
        GID_VAL="$(printf '%s\n'  "${SHOW}" | awk -F': *' '/^GID[ \t]*:/ {print $2; exit}')"
        # Quota satiri: "Quota files : 100" / "Quota size : 0"
        QFILES="$(printf '%s\n'   "${SHOW}" | awk -F': *' '/^Quota files[ \t]*:/ {print $2; exit}')"
        QSIZE="$(printf '%s\n'    "${SHOW}" | awk -F': *' '/^Quota size[ \t]*:/ {print $2; exit}')"
        # Quota size genelde "100 MB" formati — sayisal kismi cek
        QSIZE="$(printf '%s' "${QSIZE}" | grep -oE '^[0-9]+' || echo "")"
    else
        # quick path: pure-pw list 2. sütunundan home
        HOMEDIR="$(printf '%s' "${LINE}" | awk '{print $2}')"
    fi

    [[ -z "${UID_VAL}" ]]  && UID_VAL=0
    [[ -z "${GID_VAL}" ]]  && GID_VAL=0
    [[ -z "${QFILES}" ]]   && QFILES=0
    [[ -z "${QSIZE}" ]]    && QSIZE=0

    USER_OBJ="$(jq -nc \
        --arg username "${UNAME}" \
        --arg homedir  "${HOMEDIR}" \
        --argjson uid          "${UID_VAL}" \
        --argjson gid          "${GID_VAL}" \
        --argjson quota_files  "${QFILES}" \
        --argjson quota_size_mb "${QSIZE}" \
        '{
            username: $username, homedir: $homedir,
            uid: $uid, gid: $gid,
            quota_files: $quota_files, quota_size_mb: $quota_size_mb
        }')"

    USERS_JSON="$(echo "${USERS_JSON}" | jq -c --argjson u "${USER_OBJ}" '. + [$u]')"
    COUNT=$((COUNT + 1))
done <<< "${ALL_USERS}"

onx_log "ftp-pure-user-list: filter=${FILTER} count=${COUNT}"

jq -nc \
    --argjson count "${COUNT}" \
    --argjson users "${USERS_JSON}" \
    '{ ok: true, count: $count, users: $users }'
