#!/usr/bin/env bash set -Eeuo pipefail IFS=$'\n\t' readonly SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)" readonly REPOSITORY_DIR="$(cd -- "$SCRIPT_DIR/.." && pwd -P)" readonly NGINX_AVAILABLE="/etc/nginx/sites-available/meovv-mail" readonly NGINX_ENABLED="/etc/nginx/sites-enabled/meovv-mail" readonly CERTBOT_WEBROOT="/var/www/certbot" readonly CERTBOT_HOOK="/etc/letsencrypt/renewal-hooks/deploy/meovv-mail" readonly MAILCTL_BIN="/usr/local/bin/mailctl" readonly MANAGED_MARKER="Managed by MEOVV Mail installer" readonly MEOVV_RELEASE="0.1.0" COMMAND="" MAIL_HOSTNAME="" ADMIN_EMAIL="" BUNDLE_DIR="$REPOSITORY_DIR" ASSUME_YES=false CONFIGURE_DNS=false DNS_ZONE="" PUBLIC_IPV4="" PUBLIC_IPV6="" TEMP_CONTAINER="" TEMP_FILES=() CF_API_TOKEN="" CF_ZONE_ID="" log() { printf '\n\033[1;35m==>\033[0m %s\n' "$*" } warn() { printf '\033[1;33mWARNING:\033[0m %s\n' "$*" >&2 } die() { printf '\033[1;31mERROR:\033[0m %s\n' "$*" >&2 exit 1 } cleanup() { if [[ -n "$TEMP_CONTAINER" ]]; then docker rm -f "$TEMP_CONTAINER" >/dev/null 2>&1 || true fi local temporary_file for temporary_file in "${TEMP_FILES[@]}"; do rm -f -- "$temporary_file" done } trap cleanup EXIT usage() { cat <<'EOF' Install and operate MEOVV Mail prerequisites on Ubuntu 24.04/26.04 or Debian 13. Usage: sudo ./scripts/install-server.sh install \ --hostname mail.example.com \ --email admin@example.com \ [--configure-dns] [--dns-zone example.com] \ [--public-ipv4 203.0.113.10] [--public-ipv6 2001:db8::10] \ [--bundle-dir /opt/meovv-mail] [--yes] sudo ./scripts/install-server.sh finalize \ [--bundle-dir /opt/meovv-mail] [--yes] sudo ./scripts/install-server.sh status \ [--bundle-dir /opt/meovv-mail] Commands: install Install Docker, Nginx, and Certbot; initialize the bundle; obtain TLS; install proxy/renewal configuration; and start the appliance. finalize After completing the browser wizard and creating a permanent administrator, register TLS with Stalwart and remove recovery access. status Show service, certificate, and local endpoint status without changes. This script does not modify PTR records, provider firewalls, SSH, or UFW. Interactive installs can optionally configure supported Cloudflare DNS records; DNS is unchanged when that option is declined. For unattended DNS setup, use --configure-dns and provide the token through CLOUDFLARE_API_TOKEN; the token is never written to disk. EOF } parse_arguments() { [[ $# -gt 0 ]] || { usage; exit 2; } COMMAND="$1" shift while [[ $# -gt 0 ]]; do case "$1" in --hostname) [[ $# -ge 2 ]] || die "--hostname requires a value" MAIL_HOSTNAME="$2" shift 2 ;; --email) [[ $# -ge 2 ]] || die "--email requires a value" ADMIN_EMAIL="$2" shift 2 ;; --bundle-dir) [[ $# -ge 2 ]] || die "--bundle-dir requires a value" BUNDLE_DIR="$2" shift 2 ;; --configure-dns) CONFIGURE_DNS=true shift ;; --dns-zone) [[ $# -ge 2 ]] || die "--dns-zone requires a value" DNS_ZONE="$2" shift 2 ;; --public-ipv4) [[ $# -ge 2 ]] || die "--public-ipv4 requires a value" PUBLIC_IPV4="$2" shift 2 ;; --public-ipv6) [[ $# -ge 2 ]] || die "--public-ipv6 requires a value" PUBLIC_IPV6="$2" shift 2 ;; --yes|-y) ASSUME_YES=true shift ;; --help|-h) usage exit 0 ;; *) die "unknown argument: $1" ;; esac done case "$COMMAND" in install|finalize|status) ;; *) die "unknown command: $COMMAND" ;; esac [[ "$BUNDLE_DIR" = /* ]] || die "--bundle-dir must be an absolute path" [[ "$BUNDLE_DIR" != *$'\n'* ]] || die "--bundle-dir contains a newline" if [[ "$COMMAND" != "install" ]] && \ { $CONFIGURE_DNS || [[ -n "$DNS_ZONE$PUBLIC_IPV4$PUBLIC_IPV6" ]]; }; then die "DNS options are valid only with the install command" fi } require_root() { [[ ${EUID:-$(id -u)} -eq 0 ]] || die "run this command with sudo or as root" } validate_hostname() { [[ "$MAIL_HOSTNAME" =~ ^[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])?)+$ ]] || \ die "invalid fully-qualified hostname: $MAIL_HOSTNAME" [[ ${#MAIL_HOSTNAME} -le 253 ]] || die "hostname is too long" MAIL_HOSTNAME="${MAIL_HOSTNAME,,}" } validate_email() { [[ "$ADMIN_EMAIL" =~ ^[^[:space:]@]+@[^[:space:]@]+\.[^[:space:]@]+$ ]] || \ die "invalid email address: $ADMIN_EMAIL" } require_bundle() { [[ -f "$BUNDLE_DIR/compose.yaml" ]] || die "compose.yaml not found in $BUNDLE_DIR" [[ -f "$BUNDLE_DIR/Dockerfile" ]] || die "Dockerfile not found in $BUNDLE_DIR" [[ -f "$BUNDLE_DIR/deploy/nginx/meovv-mail.conf.example" ]] || die "Nginx template is missing" [[ -x "$BUNDLE_DIR/deploy/certbot/deploy-hook.sh" ]] || die "Certbot hook is missing or not executable" } confirm_install() { $ASSUME_YES && return [[ -t 0 ]] || die "non-interactive use requires --yes" cat </dev/null | sed -n 's/^ip=//p' | head -n 1 } cloudflare_api() { local method="$1" path="$2" data="${3:-}" local arguments=( --fail-with-body --silent --show-error --request "$method" "https://api.cloudflare.com/client/v4$path" ) if [[ -n "$data" ]]; then arguments+=(--data "$data") fi # Read the authorization header from stdin so the token does not appear in # the curl process arguments or get written to a temporary file. printf 'header = "Authorization: Bearer %s"\nheader = "Content-Type: application/json"\n' \ "$CF_API_TOKEN" | curl --config - "${arguments[@]}" } require_cloudflare_success() { local response="$1" action="$2" if ! jq -e '.success == true' >/dev/null 2>&1 <<< "$response"; then local detail detail="$(jq -r '[.errors[]? | (.code|tostring) + ": " + .message] | join("; ")' <<< "$response" 2>/dev/null || true)" die "Cloudflare could not $action${detail:+: $detail}" fi } cloudflare_records() { local type="$1" name="$2" response response="$(cloudflare_api GET "/zones/$CF_ZONE_ID/dns_records?type=$type&name=$name&per_page=100")" || \ die "Cloudflare DNS lookup failed for $name" require_cloudflare_success "$response" "read $type records for $name" printf '%s' "$response" } write_cloudflare_record() { local action="$1" record_id="$2" body="$3" response if [[ "$action" == "create" ]]; then response="$(cloudflare_api POST "/zones/$CF_ZONE_ID/dns_records" "$body")" || \ die "Cloudflare DNS record creation failed" else response="$(cloudflare_api PUT "/zones/$CF_ZONE_ID/dns_records/$record_id" "$body")" || \ die "Cloudflare DNS record update failed" fi require_cloudflare_success "$response" "$action a DNS record" } ensure_cloudflare_record() { local type="$1" name="$2" content="$3" priority="${4:-}" response count exact_id record_id body response="$(cloudflare_records "$type" "$name")" count="$(jq '.result | length' <<< "$response")" if [[ "$type" == "MX" ]]; then exact_id="$(jq -r --arg content "$content" --argjson priority "$priority" \ '.result[] | select(.content == $content and .priority == $priority) | .id' <<< "$response" | head -n 1)" body="$(jq -cn --arg type "$type" --arg name "$name" --arg content "$content" \ --argjson priority "$priority" '{type:$type,name:$name,content:$content,priority:$priority,ttl:1}')" else exact_id="$(jq -r --arg content "$content" \ '.result[] | select(.content == $content and .proxied == false) | .id' <<< "$response" | head -n 1)" body="$(jq -cn --arg type "$type" --arg name "$name" --arg content "$content" \ '{type:$type,name:$name,content:$content,ttl:1,proxied:false}')" fi if (( count > 1 )); then die "multiple Cloudflare $type records exist for $name; review them manually instead of replacing them" fi if [[ -n "$exact_id" ]]; then log "Cloudflare $type record is already correct: $name" return fi if (( count == 1 )); then record_id="$(jq -r '.result[0].id' <<< "$response")" write_cloudflare_record update "$record_id" "$body" log "Updated Cloudflare $type record: $name" else write_cloudflare_record create "" "$body" log "Created Cloudflare $type record: $name" fi } ensure_cloudflare_txt_default() { local name="$1" prefix="$2" content="$3" response exact existing body response="$(cloudflare_records TXT "$name")" exact="$(jq -r --arg content "$content" '.result[] | select(.content == $content) | .id' \ <<< "$response" | head -n 1)" if [[ -n "$exact" ]]; then log "Cloudflare TXT record is already correct: $name" return fi existing="$(jq -r --arg prefix "$prefix" '.result[] | select(.content | startswith($prefix)) | .content' \ <<< "$response" | head -n 1)" if [[ -n "$existing" ]]; then warn "Keeping the existing TXT policy for $name: $existing" return fi body="$(jq -cn --arg name "$name" --arg content "$content" \ '{type:"TXT",name:$name,content:$content,ttl:1}')" write_cloudflare_record create "" "$body" log "Created conservative Cloudflare TXT policy: $name" } wait_for_cloudflare_dns() { log "Waiting for the mail hostname to appear in public DNS" local attempt answer for attempt in {1..20}; do if [[ -n "$PUBLIC_IPV4" ]]; then answer="$(dig +short A "$MAIL_HOSTNAME" @1.1.1.1 | grep -Fx "$PUBLIC_IPV4" || true)" else answer="$(dig +short AAAA "$MAIL_HOSTNAME" @1.1.1.1 | grep -Fxi "$PUBLIC_IPV6" || true)" fi [[ -n "$answer" ]] && return sleep 3 done die "Cloudflare accepted the DNS records, but $MAIL_HOSTNAME is not publicly visible yet; wait briefly and rerun the installer" } configure_cloudflare_dns() { DNS_ZONE="${DNS_ZONE:-${ADMIN_EMAIL##*@}}" local detected_ipv4 detected_ipv6 answer response zone_count detected_ipv4="${PUBLIC_IPV4:-$(discover_public_address 4 || true)}" detected_ipv6="$(discover_public_address 6 || true)" if [[ -t 0 ]] && ! $ASSUME_YES; then read -r -p "Cloudflare zone [$DNS_ZONE]: " answer DNS_ZONE="${answer:-$DNS_ZONE}" read -r -p "Public IPv4 [$detected_ipv4]: " answer PUBLIC_IPV4="${answer:-$detected_ipv4}" if [[ -z "$PUBLIC_IPV6" ]]; then read -r -p "Public IPv6 (optional; detected $detected_ipv6, blank to skip): " PUBLIC_IPV6 fi else PUBLIC_IPV4="$detected_ipv4" fi validate_dns_inputs CF_API_TOKEN="${CLOUDFLARE_API_TOKEN:-}" unset CLOUDFLARE_API_TOKEN || true if [[ -z "$CF_API_TOKEN" ]] && [[ -t 0 ]]; then cat <