#!/bin/bash

# Append a hostname to Nextcloud's trusted_domains array — required for any
# host Nextcloud should accept HTTP requests on. The index is auto-picked as
# `last + 1` from the existing array so we never collide.

appNextcloudAddTrustedDomain() {
    local args="$1"
    local domain
    domain="$(authToolArg "$args" domain)"
    [[ -z "$domain" ]] && { isError "Domain is required."; return 1; }

    local current_count
    current_count=$(runFileOp docker exec -u www-data nextcloud-service php occ config:system:get trusted_domains 2>/dev/null | grep -c '^\s*[0-9]')
    [[ -z "$current_count" || "$current_count" -lt 1 ]] && current_count=1

    local out
    out=$(runFileOp docker exec -u www-data nextcloud-service php occ config:system:set trusted_domains "$current_count" --value="$domain" 2>&1)
    if echo "$out" | grep -qi "system config value\|set to string"; then
        isSuccessful "Nextcloud trusted_domains[$current_count] = $domain"
        return 0
    fi
    isError "Nextcloud add-trusted-domain failed: $out"; return 1
}
