#!/usr/bin/env bash
# gniza4cp/lib/accounts.sh — cPanel account discovery, include/exclude filtering

get_all_accounts() {
    if [[ -f /etc/trueuserdomains ]]; then
        awk '{print $2}' /etc/trueuserdomains | sort -u
    elif command -v whmapi1 &>/dev/null; then
        whmapi1 listaccts --output=jsonpretty 2>/dev/null \
            | grep -oP '"user"\s*:\s*"\K[^"]+' | sort -u
    else
        die "Cannot discover cPanel accounts: /etc/trueuserdomains not found and whmapi1 unavailable"
    fi
}

filter_accounts() {
    local all_accounts="$1"
    local filtered=()

    # Build exclude list
    local -A excludes
    if [[ -n "$EXCLUDE_ACCOUNTS" ]]; then
        IFS=',' read -ra exc_arr <<< "$EXCLUDE_ACCOUNTS"
        for acc in "${exc_arr[@]}"; do
            acc=$(echo "$acc" | xargs)  # trim whitespace
            [[ -n "$acc" ]] && excludes["$acc"]=1
        done
    fi

    # If INCLUDE_ACCOUNTS is set, only include those
    if [[ -n "$INCLUDE_ACCOUNTS" ]]; then
        IFS=',' read -ra inc_arr <<< "$INCLUDE_ACCOUNTS"
        for acc in "${inc_arr[@]}"; do
            acc=$(echo "$acc" | xargs)
            [[ -n "$acc" && -z "${excludes[$acc]:-}" ]] && filtered+=("$acc")
        done
    else
        while IFS= read -r acc; do
            [[ -n "$acc" && -z "${excludes[$acc]:-}" ]] && filtered+=("$acc")
        done <<< "$all_accounts"
    fi

    printf '%s\n' "${filtered[@]}"
}

is_suspended() {
    local user="$1"
    [[ -e "/var/cpanel/suspended/$user" ]]
}

get_backup_accounts() {
    local skip_suspended="${1:-false}"
    local all; all=$(get_all_accounts)
    local filtered; filtered=$(filter_accounts "$all")
    if [[ "$skip_suspended" == "true" ]]; then
        while IFS= read -r acc; do
            [[ -z "$acc" ]] && continue
            if is_suspended "$acc"; then
                log_info "Skipping suspended account: $acc"
                continue
            fi
            echo "$acc"
        done <<< "$filtered"
    else
        echo "$filtered"
    fi
}

get_account_homedir() {
    local user="$1"
    if [[ -f /etc/passwd ]]; then
        getent passwd "$user" | cut -d: -f6
    else
        echo "/home/$user"
    fi
}

account_exists() {
    local user="$1"
    id "$user" &>/dev/null
}
