#!/bin/bash

set -u
set -o pipefail

install_jq() {
    if command -v jq >/dev/null 2>&1; then
        return 0
    fi

    echo "jq not found, attempting to install it..."

    if command -v dnf >/dev/null 2>&1; then
        dnf install -y jq
    elif command -v yum >/dev/null 2>&1; then
        yum install -y jq
    else
        echo "Error: neither dnf nor yum is available, cannot install jq"
        return 1
    fi

    if ! command -v jq >/dev/null 2>&1; then
        echo "Error: jq installation failed"
        return 1
    fi

    return 0
}

if ! command -v uapi >/dev/null 2>&1; then
    echo "Error: uapi command not found"
    exit 1
fi

install_jq || exit 1

for userfile in /var/cpanel/users/*; do
    [ -f "$userfile" ] || continue
    user="$(basename "$userfile")"

    uapi --output=json --user="$user" DomainInfo list_domains 2>/dev/null \
    | jq -r '
        .result.data as $d
        | (
            [ $d.main_domain ]
            + ($d.addon_domains // [])
            + ($d.sub_domains // [])
          )
        | .[]
        | select(. != null and . != "")
    '
done
