#!/usr/bin/env bash # Quick Installation for NocoDB + Caddy # Installs and configures NocoDB with a Caddy reverse proxy and automatic HTTPS. set -euo pipefail DEFAULT_INSTALL_DIR="/opt/nocodb-caddy" DOCKER_CMD=(docker) LOG_FILE="" READINESS_TIMEOUT=90 READINESS_INTERVAL=2 SPINNER_PID="" CURRENT_INSTALL_DIR="$DEFAULT_INSTALL_DIR" LANG_CODE="en" set_language() { case "${1:-}" in ru|en) LANG_CODE="$1" ;; esac } msg() { local key="$1" case "$LANG_CODE:$key" in en:answer_yes_no) echo "Please answer y or n." ;; ru:answer_yes_no) echo "Пожалуйста, ответьте y/д или n/н." ;; en:log_file) echo "Log file: $LOG_FILE" ;; ru:log_file) echo "Файл журнала: $LOG_FILE" ;; en:last_log_lines) echo "Last log lines:" ;; ru:last_log_lines) echo "Последние строки журнала:" ;; en:error_details) echo "Error details:" ;; ru:error_details) echo "Детали ошибки:" ;; en:recent_error_output) echo "Recent error output:" ;; ru:recent_error_output) echo "Недавний вывод с ошибками:" ;; en:likely_cause) echo "Likely cause:" ;; ru:likely_cause) echo "Вероятная причина:" ;; en:letsencrypt_rate_limit) echo "Let's Encrypt rate limit prevented Caddy from obtaining a certificate for the configured domain." ;; ru:letsencrypt_rate_limit) echo "Ограничение Let's Encrypt не позволило Caddy получить сертификат для указанного домена." ;; en:containers_not_healthy) echo "One or more containers are not healthy or not running. Check the container status and logs below." ;; ru:containers_not_healthy) echo "Один или несколько контейнеров не работают или не находятся в состоянии healthy. Проверьте их статус и логи ниже." ;; en:domain_not_resolved) echo "The domain could not be resolved from the server. Check the DNS records for the configured domain." ;; ru:domain_not_resolved) echo "Сервер не смог разрешить домен. Проверьте DNS-записи для указанного домена." ;; en:http_https_unreachable) echo "The server could not reach the domain over HTTP or HTTPS. Check firewall rules, port forwarding, and whether Caddy is listening on ports 80 and 443." ;; ru:http_https_unreachable) echo "Сервер не смог подключиться к домену по HTTP или HTTPS. Проверьте правила firewall, проброс портов и прослушивает ли Caddy порты 80 и 443." ;; en:tls_failing) echo "HTTP is reachable, but HTTPS/TLS is failing. Check Caddy certificate issuance and TLS configuration." ;; ru:tls_failing) echo "HTTP доступен, но HTTPS/TLS не работает. Проверьте выпуск сертификата в Caddy и конфигурацию TLS." ;; en:nocodb_started_public_unavailable) echo "NocoDB started, but the public HTTPS endpoint is still unavailable. Check Caddy, TLS issuance, and external access to the domain." ;; ru:nocodb_started_public_unavailable) echo "NocoDB запустился, но публичный HTTPS-адрес все еще недоступен. Проверьте Caddy, выпуск TLS-сертификата и внешний доступ к домену." ;; en:https_timeout) echo "The HTTPS endpoint did not become reachable within the timeout. Review the container status, probes, and logs below." ;; ru:https_timeout) echo "HTTPS-адрес не стал доступен за отведенное время. Проверьте статус контейнеров, результаты проверок и логи ниже." ;; en:readiness_diagnostics) echo "Readiness diagnostics:" ;; ru:readiness_diagnostics) echo "Диагностика готовности:" ;; en:troubleshooting_commands) echo "Troubleshooting commands:" ;; ru:troubleshooting_commands) echo "Команды для диагностики:" ;; en:installation_failed) echo "Installation failed." ;; ru:installation_failed) echo "Установка завершилась с ошибкой." ;; en:ok) echo "[OK]" ;; ru:ok) echo "[OK]" ;; en:fail) echo "[FAIL]" ;; ru:fail) echo "[FAIL]" ;; en:no_package_manager) echo "No supported package manager found to install $2." ;; ru:no_package_manager) echo "Не найден поддерживаемый менеджер пакетов для установки $2." ;; en:linux_only) echo "This installer supports Linux only." ;; ru:linux_only) echo "Этот установщик поддерживает только Linux." ;; en:root_required) echo "This action requires root privileges. Run the script as root or install sudo." ;; ru:root_required) echo "Для этого действия нужны права root. Запустите скрипт от root или установите sudo." ;; en:docker_daemon_unavailable) echo "Docker is installed, but the daemon is not running or not accessible." ;; ru:docker_daemon_unavailable) echo "Docker установлен, но его daemon не запущен или недоступен." ;; en:start_docker) echo "Start it with: sudo systemctl start docker" ;; ru:start_docker) echo "Запустите его командой: sudo systemctl start docker" ;; en:enable_docker) echo "To enable autostart: sudo systemctl enable docker" ;; ru:enable_docker) echo "Чтобы включить автозапуск: sudo systemctl enable docker" ;; en:start_daemon_retry) echo "Start the Docker daemon and run the script again." ;; ru:start_daemon_retry) echo "Запустите Docker daemon и повторите запуск скрипта." ;; en:wait_starting) echo "Starting NocoDB and Caddy containers..." ;; ru:wait_starting) echo "Запускаем контейнеры NocoDB и Caddy..." ;; en:wait_running) echo "Containers are running." ;; ru:wait_running) echo "Контейнеры запущены." ;; en:wait_http_ready) echo "Domain is responding over HTTP." ;; ru:wait_http_ready) echo "Домен отвечает по HTTP." ;; en:wait_tls_pending) echo "Waiting for Caddy to provision the TLS certificate..." ;; ru:wait_tls_pending) echo "Ожидание выпуска TLS-сертификата в Caddy..." ;; en:waiting_nocodb) echo "Waiting for NocoDB to become available..." ;; ru:waiting_nocodb) echo "Ожидание доступности NocoDB..." ;; en:warning_public_ip) echo "Warning: Could not determine the server's public IPv4 address." ;; ru:warning_public_ip) echo "Предупреждение: не удалось определить публичный IPv4-адрес сервера." ;; en:warning_resolve_a) echo "Warning: Could not resolve the domain's A record." ;; ru:warning_resolve_a) echo "Предупреждение: не удалось получить A-запись домена." ;; en:warning_no_a_continue) echo "Warning: The domain does not have an A record. Continue anyway?" ;; ru:warning_no_a_continue) echo "Предупреждение: у домена нет A-записи. Продолжить?" ;; en:warning_domain_not_pointing) echo "Warning: The domain does not appear to point to this server." ;; ru:warning_domain_not_pointing) echo "Предупреждение: домен, похоже, не указывает на этот сервер." ;; en:server_ipv4) echo "Server IPv4: $2" ;; ru:server_ipv4) echo "IPv4 сервера: $2" ;; en:domain_a_records) echo "Domain A records:" ;; ru:domain_a_records) echo "A-записи домена:" ;; en:continue_anyway) echo "Continue anyway?" ;; ru:continue_anyway) echo "Все равно продолжить?" ;; en:docker_login_recommended) echo "Docker Hub login is recommended to avoid image pull rate limits." ;; ru:docker_login_recommended) echo "Рекомендуется войти в Docker Hub, чтобы избежать лимитов на скачивание образов." ;; en:docker_login_now) echo "Log in to Docker Hub now?" ;; ru:docker_login_now) echo "Войти в Docker Hub сейчас?" ;; en:downloader_required) echo "curl or wget is required. Installing curl..." ;; ru:downloader_required) echo "Требуется curl или wget. Устанавливаем curl..." ;; en:downloader_install_failed) echo "Failed to install a downloader for the Docker installer." ;; ru:downloader_install_failed) echo "Не удалось установить загрузчик для установщика Docker." ;; en:docker_installing) echo "Installing Docker and Docker Compose plugin..." ;; ru:docker_installing) echo "Устанавливаем Docker и плагин Docker Compose..." ;; en:download_docker_installer) echo "Downloading Docker installer..." ;; ru:download_docker_installer) echo "Скачивание установщика Docker..." ;; en:run_docker_installer) echo "Running Docker installer..." ;; ru:run_docker_installer) echo "Запуск установщика Docker..." ;; en:docker_install_done) echo "Docker installation completed." ;; ru:docker_install_done) echo "Установка Docker завершена." ;; en:docker_not_installed) echo "Docker is not installed." ;; ru:docker_not_installed) echo "Docker не установлен." ;; en:compose_not_installed) echo "Docker Compose plugin is not installed." ;; ru:compose_not_installed) echo "Плагин Docker Compose не установлен." ;; en:docker_install_failed) echo "Docker installation failed." ;; ru:docker_install_failed) echo "Установка Docker завершилась с ошибкой." ;; en:checking_docker) echo "Checking installed Docker availability..." ;; ru:checking_docker) echo "Проверка доступности установленного Docker..." ;; en:compose_install_failed) echo "Docker Compose plugin installation failed." ;; ru:compose_install_failed) echo "Не удалось установить плагин Docker Compose." ;; en:overwrite_prompt) printf '%s already exists at %s. Overwrite it?' "$2" "$3" ;; ru:overwrite_prompt) printf '%s уже существует по пути %s. Перезаписать?' "$2" "$3" ;; en:installer_title) echo "This script installs NocoDB and Caddy." ;; ru:installer_title) echo "Это скрипт для установки NocoDB и Caddy" ;; en:installation_directory) echo "Installation directory" ;; ru:installation_directory) echo "Каталог установки" ;; en:leave_blank_for) printf '%s (leave blank for %s)' "$2" "$3" ;; ru:leave_blank_for) printf '%s (оставьте пустым для %s)' "$2" "$3" ;; en:nocodb_already_installed) echo "NocoDB is already installed at $2." ;; ru:nocodb_already_installed) echo "NocoDB уже установлен в $2." ;; en:choose_action) echo "Choose action: [R]econfigure, [S]tart/restart, or [E]xit" ;; ru:choose_action) echo "Выберите действие: [R] перенастроить, [S] запустить/перезапустить или [E] выйти" ;; en:answer_rse) echo "Please answer R, S, or E." ;; ru:answer_rse) echo "Пожалуйста, ответьте R, S или E." ;; en:domain_empty) echo "Domain cannot be empty." ;; ru:domain_empty) echo "Домен не может быть пустым." ;; en:domain_invalid_format) echo "Use only a domain or subdomain without protocol, port, path, or spaces." ;; ru:domain_invalid_format) echo "Укажите только домен или поддомен без протокола, порта, пути и пробелов." ;; en:domain_incorrect) echo "Error: The domain is not correct." ;; ru:domain_incorrect) echo "Ошибка: домен указан некорректно." ;; en:keeping_existing_compose) echo "Keeping existing docker-compose.yml" ;; ru:keeping_existing_compose) echo "Сохраняем существующий docker-compose.yml" ;; en:keeping_existing_caddyfile) echo "Keeping existing Caddyfile" ;; ru:keeping_existing_caddyfile) echo "Сохраняем существующий Caddyfile" ;; en:nothing_to_do) echo "Nothing to do." ;; ru:nothing_to_do) echo "Нечего выполнять." ;; en:configured_domain_not_found) echo "Could not determine the configured domain from $2/Caddyfile." ;; ru:configured_domain_not_found) echo "Не удалось определить настроенный домен из $2/Caddyfile." ;; en:use_reconfigure_mode) echo "Use reconfigure mode to set the domain again." ;; ru:use_reconfigure_mode) echo "Используйте режим перенастройки, чтобы заново указать домен." ;; en:enter_domain) echo "Enter domain or subdomain (example: nocodb.mysite.com)" ;; ru:enter_domain) echo "Введите домен или поддомен (пример: nocodb.mysite.com)" ;; en:starting_containers) echo "Starting containers..." ;; ru:starting_containers) echo "Запуск контейнеров..." ;; en:nocodb_available) echo "NocoDB is now available." ;; ru:nocodb_available) echo "NocoDB теперь доступен." ;; en:nocodb_timeout) echo "Error: NocoDB did not become available within $READINESS_TIMEOUT seconds." ;; ru:nocodb_timeout) echo "Ошибка: NocoDB не стал доступен в течение $READINESS_TIMEOUT секунд." ;; en:nocodb_installed_success) echo "Installation completed successfully." ;; ru:nocodb_installed_success) echo "Установка прошла успешно." ;; en:open_nocodb) echo "Open: https://$2" ;; ru:open_nocodb) echo "Открыть: https://$2" ;; en:useful_commands) echo "Useful commands:" ;; ru:useful_commands) echo "Полезные команды:" ;; *) echo "$key" ;; esac } yn_prompt() { if [[ "$LANG_CODE" == "ru" ]]; then printf '[д/Н]' else printf '[y/N]' fi } is_yes_answer() { case "$1" in [Yy]|[Дд]) return 0 ;; *) return 1 ;; esac } is_no_answer() { case "$1" in ""|[Nn]|[Нн]) return 0 ;; *) return 1 ;; esac } parse_args() { while [[ $# -gt 0 ]]; do case "$1" in --lang) if [[ $# -lt 2 ]]; then echo "Missing value for --lang." >&2 exit 1 fi set_language "$2" shift 2 ;; --lang=*) set_language "${1#*=}" shift ;; *) break ;; esac done REMAINING_ARGS=("$@") } has_command() { command -v "$1" >/dev/null 2>&1 } confirm_action() { local message="$1" local answer="" while true; do read -r -p "$message $(yn_prompt): " answer if is_yes_answer "$answer"; then return 0 fi if is_no_answer "$answer"; then return 1 fi msg answer_yes_no done } init_log_file() { LOG_FILE="$(mktemp -t nocodb-caddy-install.XXXXXX.log)" } print_log_hint() { if [[ -n "$LOG_FILE" && -f "$LOG_FILE" ]]; then msg log_file fi } print_log_tail() { if [[ -n "$LOG_FILE" && -f "$LOG_FILE" ]]; then echo msg last_log_lines tail -n 20 "$LOG_FILE" || true fi } print_recent_error_context() { local error_summary="" local daemon_error="" if [[ -n "$LOG_FILE" && -f "$LOG_FILE" ]]; then daemon_error="$( tail -n 50 "$LOG_FILE" \ | sed 's/\r$//' \ | grep -F 'Error response from daemon:' \ | tail -n 1 \ || true )" error_summary="$daemon_error" if [[ -z "$error_summary" ]]; then error_summary="$( tail -n 50 "$LOG_FILE" \ | sed 's/\r$//' \ | grep -E '([Ee]rror|[Ff]ailed|denied|unauthorized|no space left|cannot allocate|port is already allocated)' \ | tail -n 3 \ || true )" fi if [[ -n "$error_summary" ]]; then msg error_details printf '%s\n' "$error_summary" else msg recent_error_output tail -n 12 "$LOG_FILE" || true fi fi } print_readiness_failure_summary() { local ps_output="$1" local caddy_logs="$2" local nocodb_logs="$3" local http_probe="$4" local https_probe="$5" echo msg likely_cause if grep -qi 'rateLimited\|too many certificates' <<<"$caddy_logs"; then msg letsencrypt_rate_limit return fi if grep -Eqi '(^|[[:space:]])(exited|restarting|created|dead)([[:space:]]|$)' <<<"$ps_output"; then msg containers_not_healthy return fi if grep -qi 'Could not resolve host' <<<"$http_probe$https_probe"; then msg domain_not_resolved return fi if grep -qi 'Connection refused\|Failed to connect\|timed out' <<<"$http_probe$https_probe"; then msg http_https_unreachable return fi if grep -q '308 Permanent Redirect' <<<"$http_probe" && grep -qi 'tlsv1 alert\|SSL routines\|handshake failure\|no alternative certificate subject name\|certificate' <<<"$https_probe$caddy_logs"; then msg tls_failing return fi if grep -qi 'Nest application successfully started\|App started successfully' <<<"$nocodb_logs"; then msg nocodb_started_public_unavailable return fi msg https_timeout } print_readiness_debug_info() { local address="$1" local install_dir="$2" local ps_output="" local caddy_logs="" local nocodb_logs="" local http_probe="" local https_probe="" echo msg readiness_diagnostics if [[ -f "$install_dir/docker-compose.yml" ]]; then ps_output="$(docker_cli compose -f "$install_dir/docker-compose.yml" ps --all 2>&1 || true)" caddy_logs="$(docker_cli compose -f "$install_dir/docker-compose.yml" logs --tail 50 caddy 2>&1 || true)" nocodb_logs="$(docker_cli compose -f "$install_dir/docker-compose.yml" logs --tail 50 nocodb 2>&1 || true)" fi if has_command curl; then http_probe="$(curl -I -sS --connect-timeout 5 "http://$address" 2>&1 || true)" https_probe="$(curl -kI -sS --connect-timeout 5 "https://$address" 2>&1 || true)" fi print_readiness_failure_summary "$ps_output" "$caddy_logs" "$nocodb_logs" "$http_probe" "$https_probe" print_log_hint echo msg troubleshooting_commands echo " ${DOCKER_CMD[*]} compose -f $install_dir/docker-compose.yml ps" echo " ${DOCKER_CMD[*]} compose -f $install_dir/docker-compose.yml logs --tail 50 caddy" echo " ${DOCKER_CMD[*]} compose -f $install_dir/docker-compose.yml logs --tail 50 nocodb" echo " curl -I http://$address" echo " curl -kI https://$address" } handle_error() { stop_spinner 1 "" echo msg installation_failed print_log_hint print_log_tail echo msg troubleshooting_commands echo " ${DOCKER_CMD[*]} compose -f $CURRENT_INSTALL_DIR/docker-compose.yml ps" echo " ${DOCKER_CMD[*]} compose -f $CURRENT_INSTALL_DIR/docker-compose.yml logs --tail 50" } run_quiet() { "$@" >>"$LOG_FILE" 2>&1 } start_spinner() { local message="$1" if [[ ! -t 1 ]]; then echo "$message" return fi ( local frames='|/-\' local i=0 while true; do printf '\r%s %s' "${frames:i++%${#frames}:1}" "$message" sleep 0.1 done ) & SPINNER_PID=$! } stop_spinner() { local exit_code="${1:-0}" local message="${2-}" if [[ -n "$SPINNER_PID" ]]; then kill "$SPINNER_PID" >/dev/null 2>&1 || true wait "$SPINNER_PID" 2>/dev/null || true SPINNER_PID="" if [[ -t 1 ]]; then printf '\r\033[K' fi fi if [[ -n "$message" ]]; then if [[ "$exit_code" -eq 0 ]]; then echo "$(msg ok) $message" else echo "$(msg fail) $message" print_log_hint print_recent_error_context fi fi } run_with_spinner() { local message="$1" shift start_spinner "$message" if "$@" >>"$LOG_FILE" 2>&1; then stop_spinner 0 "$message" return 0 fi stop_spinner 1 "$message" return 1 } package_manager_install() { local package_name="$1" if has_command apt-get; then run_as_root apt-get update run_as_root apt-get install -y "$package_name" elif has_command dnf; then run_as_root dnf install -y "$package_name" elif has_command yum; then run_as_root yum install -y "$package_name" elif has_command zypper; then run_as_root zypper --non-interactive install "$package_name" elif has_command apk; then run_as_root apk add --no-cache "$package_name" else msg no_package_manager "$package_name" exit 1 fi } require_linux() { if [[ "$(uname -s)" != "Linux" ]]; then msg linux_only exit 1 fi } run_as_root() { if [[ "${EUID:-$(id -u)}" -eq 0 ]]; then "$@" elif has_command sudo; then sudo "$@" else msg root_required exit 1 fi } docker_cli() { "${DOCKER_CMD[@]}" "$@" } set_docker_cmd() { if ! has_command docker; then return fi if docker info >/dev/null 2>&1; then DOCKER_CMD=(docker) elif has_command sudo; then DOCKER_CMD=(sudo docker) else DOCKER_CMD=(docker) fi } print_docker_start_hint() { msg docker_daemon_unavailable if has_command systemctl; then msg start_docker msg enable_docker else msg start_daemon_retry fi } get_public_ipv4() { local ip="" local service="" for service in "https://api.ipify.org" "https://ipv4.icanhazip.com"; do if ip="$(curl -4fsSL "$service" 2>/dev/null)"; then ip="${ip//$'\r'/}" ip="${ip//$'\n'/}" if [[ "$ip" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]; then printf '%s' "$ip" return 0 fi fi done return 1 } resolve_domain_ipv4_public() { local domain="$1" local resolved_ips="" local response="" local resolver="" if has_command dig; then for resolver in "1.1.1.1" "8.8.8.8"; do resolved_ips="$( dig @"$resolver" +short A "$domain" 2>/dev/null | sed '/^$/d' || true )" if [[ -n "$resolved_ips" ]]; then printf '%s\n' "$resolved_ips" | sort -u return 0 fi done fi if has_command curl; then for resolver in \ "https://dns.google/resolve?name=$domain&type=A" \ "https://cloudflare-dns.com/dns-query?name=$domain&type=A" do if response="$(curl -fsSL -H 'accept: application/dns-json' "$resolver" 2>/dev/null)"; then resolved_ips="$( printf '%s' "$response" \ | grep -oE '"data":"([0-9]{1,3}\.){3}[0-9]{1,3}"' \ | sed -E 's/^"data":"//; s/"$//' \ | sort -u \ || true )" if [[ -n "$resolved_ips" ]]; then printf '%s\n' "$resolved_ips" return 0 fi fi done fi return 1 } resolve_domain_ipv4_local() { local domain="$1" if has_command getent; then getent ahostsv4 "$domain" | awk '{print $1}' | sort -u elif has_command dig; then dig +short A "$domain" | sed '/^$/d' elif has_command host; then host -t A "$domain" | awk '/has address/ {print $NF}' else return 1 fi } resolve_domain_ipv4() { local domain="$1" if resolve_domain_ipv4_public "$domain"; then return 0 fi resolve_domain_ipv4_local "$domain" } print_wait_step_once() { local printed_var="$1" local message="$2" if [[ "${!printed_var:-false}" == "true" ]]; then return fi printf -v "$printed_var" '%s' "true" if [[ -n "$SPINNER_PID" && -t 1 ]]; then printf '\r\033[K' fi echo " - $message" } is_successful_http_response() { local response="$1" local status_code="" status_code="$( printf '%s\n' "$response" \ | sed -nE 's/^HTTP\/[0-9.]+ ([0-9]{3}).*/\1/p' \ | tail -n 1 )" if [[ -z "$status_code" ]]; then return 1 fi [[ "$status_code" =~ ^(200|301|302|303|307|308|401|403)$ ]] } wait_for_nocodb() { local address="$1" local install_dir="$2" local elapsed=0 local ps_output="" local caddy_logs="" local http_probe="" local https_probe="" local printed_starting="false" local printed_running="false" local printed_http_ready="false" local printed_tls_pending="false" start_spinner "$(msg waiting_nocodb)" print_wait_step_once printed_starting "$(msg wait_starting)" while (( elapsed < READINESS_TIMEOUT )); do https_probe="$(curl -kI -sS --connect-timeout 5 "https://$address" 2>&1 || true)" if is_successful_http_response "$https_probe"; then stop_spinner 0 "$(msg waiting_nocodb)" return 0 fi ps_output="$(docker_cli compose -f "$install_dir/docker-compose.yml" ps --all 2>&1 || true)" if grep -Eqi '(^|[[:space:]])up([[:space:]]|$)' <<<"$ps_output"; then print_wait_step_once printed_running "$(msg wait_running)" fi http_probe="$(curl -I -sS --connect-timeout 5 "http://$address" 2>&1 || true)" if is_successful_http_response "$http_probe"; then print_wait_step_once printed_http_ready "$(msg wait_http_ready)" fi caddy_logs="$(docker_cli compose -f "$install_dir/docker-compose.yml" logs --tail 20 caddy 2>&1 || true)" if grep -qi 'obtaining certificate\|authorization finalized\|waiting on internal rate limiter\|rateLimited\|too many certificates' <<<"$caddy_logs$https_probe"; then print_wait_step_once printed_tls_pending "$(msg wait_tls_pending)" fi if ! docker_cli compose -f "$install_dir/docker-compose.yml" ps --status running >/dev/null 2>&1; then break fi sleep "$READINESS_INTERVAL" elapsed=$((elapsed + READINESS_INTERVAL)) done stop_spinner 0 "" return 1 } confirm_domain_points_to_server() { local domain="$1" local server_ip="" local resolved_ips="" if ! server_ip="$(get_public_ipv4)"; then msg warning_public_ip return 0 fi if ! resolved_ips="$(resolve_domain_ipv4 "$domain")"; then msg warning_resolve_a return 0 fi if [[ -z "$resolved_ips" ]]; then if ! confirm_action "$(msg warning_no_a_continue)"; then return 1 fi return 0 fi if grep -Fxq "$server_ip" <<<"$resolved_ips"; then return 0 fi msg warning_domain_not_pointing msg server_ipv4 "$server_ip" msg domain_a_records printf '%s\n' "$resolved_ips" if ! confirm_action "$(msg continue_anyway)"; then return 1 fi return 0 } offer_docker_login() { echo msg docker_login_recommended if confirm_action "$(msg docker_login_now)"; then docker_cli login fi } download_file() { local url="$1" local output_path="$2" if has_command curl; then curl -fsSL "$url" -o "$output_path" else if ! has_command wget; then msg downloader_required package_manager_install curl fi if has_command curl; then curl -fsSL "$url" -o "$output_path" elif has_command wget; then wget -qO "$output_path" "$url" else msg downloader_install_failed exit 1 fi fi } install_docker_stack() { local installer installer="$(mktemp)" msg docker_installing run_with_spinner "$(msg download_docker_installer)" download_file "https://get.docker.com" "$installer" run_with_spinner "$(msg run_docker_installer)" run_as_root sh "$installer" rm -f "$installer" msg docker_install_done } ensure_docker_stack() { local need_install=false if ! has_command docker; then msg docker_not_installed need_install=true fi if has_command docker && ! docker compose version >/dev/null 2>&1; then msg compose_not_installed need_install=true fi if [[ "$need_install" == true ]]; then install_docker_stack fi set_docker_cmd if ! has_command docker; then msg docker_install_failed exit 1 fi msg checking_docker if ! docker_cli info >/dev/null 2>&1; then print_docker_start_hint exit 1 fi if ! docker_cli compose version >/dev/null 2>&1; then msg compose_install_failed exit 1 fi } create_install_dir() { local install_dir="$1" local install_dir_existed=false local nocodb_dir_existed=false [[ -d "$install_dir" ]] && install_dir_existed=true [[ -d "$install_dir/nocodb" ]] && nocodb_dir_existed=true run_as_root mkdir -p "$install_dir/nocodb" if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then if [[ "$install_dir_existed" == false ]]; then run_as_root chown "$(id -u):$(id -g)" "$install_dir" fi if [[ "$nocodb_dir_existed" == false ]]; then run_as_root chown "$(id -u):$(id -g)" "$install_dir/nocodb" fi fi } write_root_owned_file() { local destination="$1" local content="$2" printf '%s' "$content" | run_as_root tee "$destination" >/dev/null } sanitize_input() { local value="$1" value="${value//$'\r'/}" value="${value#"${value%%[![:space:]]*}"}" value="${value%"${value##*[![:space:]]}"}" printf '%s' "$value" } sanitize_domain_input() { local value="$1" value="$(sanitize_input "$value")" value="$(printf '%s' "$value" | tr -cd 'A-Za-z0-9._-')" printf '%s' "$value" } confirm_overwrite() { local file_path="$1" local description="$2" local answer="" if [[ ! -e "$file_path" ]]; then return 0 fi while true; do read -r -p "$(msg overwrite_prompt "$description" "$file_path") $(yn_prompt): " answer if is_yes_answer "$answer"; then return 0 fi if is_no_answer "$answer"; then return 1 fi msg answer_yes_no done } prompt() { local message="$1" local default_value="${2-}" local value="" local prompt_text="" if [[ -n "$default_value" ]]; then prompt_text="$(msg leave_blank_for "$message" "$default_value"): " read -r -p "$prompt_text" value value="${value:-$default_value}" else read -r -p "$message: " value fi value="$(sanitize_input "$value")" printf '%s' "$value" } prompt_existing_install_action() { local install_dir="$1" local answer="" msg nocodb_already_installed "$install_dir" >&2 while true; do read -r -p "$(msg choose_action): " answer answer="$(sanitize_input "$answer")" case "$answer" in [Rr]) printf 'reconfigure'; return 0 ;; [Ss]) printf 'restart'; return 0 ;; ""|[Ee]) printf 'exit'; return 0 ;; *) msg answer_rse >&2 ;; esac done } validate_address() { local address="$1" local domain_regex='^([a-zA-Z0-9]([-a-zA-Z0-9]{0,61}[a-zA-Z0-9])?\.)*[a-zA-Z0-9]([-a-zA-Z0-9]{0,61}[a-zA-Z0-9])?\.[a-zA-Z]{2,}$' if [[ -z "$address" ]]; then msg domain_empty return 1 fi if [[ "$address" == *://* || "$address" == */* || "$address" == *:* || "$address" =~ [[:space:]] ]]; then msg domain_invalid_format return 1 fi if [[ ! "$address" =~ $domain_regex ]]; then msg domain_incorrect return 1 fi return 0 } is_existing_installation() { local install_dir="$1" [[ -f "$install_dir/docker-compose.yml" && -f "$install_dir/Caddyfile" ]] } get_configured_address() { local install_dir="$1" if [[ ! -f "$install_dir/Caddyfile" ]]; then return 1 fi sed -nE '1s/^[[:space:]]*([^[:space:]{]+)[[:space:]]*\{[[:space:]]*$/\1/p' "$install_dir/Caddyfile" | head -n 1 } write_compose_file() { local install_dir="$1" if ! confirm_overwrite "$install_dir/docker-compose.yml" "docker-compose.yml"; then msg keeping_existing_compose return fi write_root_owned_file "$install_dir/docker-compose.yml" "$(cat <<'EOF' services: nocodb: image: nocodb/nocodb:latest restart: unless-stopped volumes: - ./nocodb:/usr/app/data expose: - "8080" caddy: image: caddy:2 restart: unless-stopped ports: - "80:80" - "443:443" volumes: - ./Caddyfile:/etc/caddy/Caddyfile:ro - caddy_data:/data - caddy_config:/config depends_on: - nocodb volumes: caddy_data: caddy_config: EOF )" } write_caddyfile() { local install_dir="$1" local address="$2" if ! confirm_overwrite "$install_dir/Caddyfile" "Caddyfile"; then msg keeping_existing_caddyfile return fi write_root_owned_file "$install_dir/Caddyfile" "$(cat <