#!/bin/bash
# Your own mail server on one Debian VM: Stalwart, with outgoing mail through SMTP2GO.
# https://outwright.app
#
# On Hetzner Cloud: fill in the values below, then paste the whole script into the
# "Cloud config" field when you create the server. It sets up DNS, reverse DNS, the
# firewall, the TLS certificate and the accounts by itself. Read the result with:
#
#     ssh root@<server address> cat /root/mail-setup.txt
#
# On any other Debian server: leave HETZNER_TOKEN empty and run it as root. DNS,
# reverse DNS and the firewall are then yours to set up; mail-setup.txt says how.

# ---- Fill in ---------------------------------------------------------------------

DOMAIN="example.org"            # your domain: addresses become name@example.org
USERS="anna erik"               # one account per name, separated by spaces
HETZNER_TOKEN=""                # Hetzner Cloud API token, Read & Write
SMTP2GO_USER=""                 # SMTP2GO: Sending > SMTP Users
SMTP2GO_PASSWORD=""
SMTP2GO_ID=""                   # the number in SMTP2GO's DNS records (s<number>._domainkey)

# ---- Nothing to change below -----------------------------------------------------

set -euo pipefail

HOST="mail.${DOMAIN}"
API="https://api.hetzner.cloud/v1"
CONF=/etc/stalwart
ENV_FILE="${CONF}/stalwart.env"
OUT=/root/mail-setup.txt
WORK=/root/mail-setup
mkdir -p "$WORK"
chmod 700 "$WORK"

log() { printf '==> %s\n' "$*"; }
die() { printf 'ERROR: %s\n' "$*" >&2; exit 1; }

[ "$(id -u)" -eq 0 ] || die "run as root"
case "$DOMAIN" in example.org|"") die "set DOMAIN at the top of the script";; esac
[ -n "$SMTP2GO_USER" ] && [ -n "$SMTP2GO_PASSWORD" ] || die "set SMTP2GO_USER and SMTP2GO_PASSWORD"

export DEBIAN_FRONTEND=noninteractive
log "Installing tools"
apt-get update -q
apt-get install -y -q curl jq openssl xz-utils ca-certificates >/dev/null

password() { openssl rand -base64 24 | tr -d '/+=' | cut -c1-20; }

# ---- Hetzner: firewall, reverse DNS and DNS records -------------------------------

# hz METHOD PATH [JSON]: prints the response body, returns 1 on an HTTP error.
hz() {
    local method="$1" path="$2" body="${3:-}" response code
    if [ -n "$body" ]; then
        response=$(curl -sS -X "$method" -H "Authorization: Bearer ${HETZNER_TOKEN}" \
            -H "Content-Type: application/json" --data "$body" -w '\n%{http_code}' "${API}${path}")
    else
        response=$(curl -sS -X "$method" -H "Authorization: Bearer ${HETZNER_TOKEN}" \
            -w '\n%{http_code}' "${API}${path}")
    fi
    code="${response##*$'\n'}"
    printf '%s' "${response%$'\n'*}"
    [ "$code" -lt 400 ]
}

# rrset NAME TYPE VALUE...: sets the records of one name and type in the zone.
rrset() {
    local name="$1" type="$2" records
    shift 2
    records=$(printf '%s\n' "$@" | jq -R '{value: .}' | jq -s '{records: ., ttl: 300}')
    hz POST "/zones/${DOMAIN}/rrsets/${name}/${type}/actions/set_records" "$records" >/dev/null \
        || hz POST "/zones/${DOMAIN}/rrsets/${name}/${type}/actions/add_records" "$records" >/dev/null \
        || die "could not set the ${type} record for ${name}"
}

NAMESERVERS=""
if [ -n "$HETZNER_TOKEN" ]; then
    SERVER_ID=$(curl -sSf http://169.254.169.254/hetzner/v1/metadata/instance-id) \
        || die "HETZNER_TOKEN is set, but this is not a Hetzner Cloud server"
    server=$(hz GET "/servers/${SERVER_ID}") || die "the Hetzner token was refused: ${server}"
    IPV4=$(jq -r '.server.public_net.ipv4.ip // empty' <<<"$server")
    IPV6=$(jq -r '.server.public_net.ipv6.ip // empty' <<<"$server" | sed 's#::/64$#::1#')
    [ -n "$IPV4" ] || die "the server has no public IPv4 address"

    log "Firewall"
    if ! hz GET "/firewalls?name=mail" | jq -e '.firewalls | length > 0' >/dev/null; then
        rules=$(jq -n '[22, 25, 465, 993, 443] | map({direction: "in", protocol: "tcp",
            port: tostring, source_ips: ["0.0.0.0/0", "::/0"]})
            + [{direction: "in", protocol: "icmp", source_ips: ["0.0.0.0/0", "::/0"]}]')
        hz POST /firewalls "$(jq -n --argjson rules "$rules" --argjson id "$SERVER_ID" \
            '{name: "mail", rules: $rules, apply_to: [{type: "server", server: {id: $id}}]}')" >/dev/null \
            || die "could not create the firewall"
    fi

    log "Reverse DNS"
    for ip in $IPV4 $IPV6; do
        hz POST "/servers/${SERVER_ID}/actions/change_dns_ptr" \
            "$(jq -n --arg ip "$ip" --arg ptr "$HOST" '{ip: $ip, dns_ptr: $ptr}')" >/dev/null \
            || die "could not set reverse DNS for ${ip}"
    done

    log "DNS zone for ${DOMAIN}"
    if ! zone=$(hz GET "/zones/${DOMAIN}"); then
        zone=$(hz POST /zones "$(jq -n --arg name "$DOMAIN" '{name: $name, mode: "primary"}')") \
            || die "could not create the DNS zone: ${zone}"
    fi
    NAMESERVERS=$(jq -r '.zone.authoritative_nameservers.assigned // [] | join(" ")' <<<"$zone")

    rrset mail A "$IPV4"
    if [ -n "$IPV6" ]; then rrset mail AAAA "$IPV6"; fi
    rrset @ MX "10 ${HOST}."
    if [ -n "$SMTP2GO_ID" ]; then
        rrset "s${SMTP2GO_ID}._domainkey" CNAME "dkim.smtp2go.net."
        rrset "em${SMTP2GO_ID}" CNAME "return.smtp2go.net."
        rrset link CNAME "track.smtp2go.net."
    fi
fi

hostnamectl set-hostname "$HOST" || true

# ---- Stalwart ----------------------------------------------------------------------

[ -e "${CONF}/config.json" ] && die "Stalwart is already set up on this server"

SETUP_PASSWORD=$(password)
ADMIN_PASSWORD=$(password)

# envline NAME VALUE: one quoted line for the systemd environment file.
envline() { printf '%s="%s"\n' "$1" "$(printf '%s' "$2" | sed 's/[\\"]/\\&/g')"; }

write_env() {
    {
        echo "# Written by the Outwright mail server setup."
        if [ -n "$HETZNER_TOKEN" ]; then envline HETZNER_TOKEN "$HETZNER_TOKEN"; fi
        envline SMTP2GO_PASSWORD "$SMTP2GO_PASSWORD"
        if [ "$1" != normal ]; then envline STALWART_RECOVERY_ADMIN "setup:${SETUP_PASSWORD}"; fi
        if [ "$1" = recovery ]; then echo 'STALWART_RECOVERY_MODE="1"'; fi
    } >"$ENV_FILE"
}

# The installer keeps an environment file that already exists, so the setup
# administrator is in place before Stalwart starts for the first time.
mkdir -p "$CONF"
write_env bootstrap
chmod 600 "$ENV_FILE"

log "Installing Stalwart"
curl --proto '=https' --tlsv1.2 -sSf https://get.stalw.art/install.sh -o "${WORK}/install.sh"
sh "${WORK}/install.sh"

log "Installing stalwart-cli"
arch=$(uname -m)
curl --proto '=https' --tlsv1.2 -sSfL \
    "https://github.com/stalwartlabs/cli/releases/latest/download/stalwart-cli-${arch}-unknown-linux-gnu.tar.xz" \
    -o "${WORK}/cli.tar.xz"
tar xJf "${WORK}/cli.tar.xz" -C "$WORK"
install -m 0755 "${WORK}/stalwart-cli-${arch}-unknown-linux-gnu/stalwart-cli" /usr/local/bin/stalwart-cli

wait_for_stalwart() {
    local i
    for i in $(seq 1 60); do
        curl -s -o /dev/null http://127.0.0.1:8080/ && return 0
        sleep 2
    done
    die "Stalwart did not start; see journalctl -u stalwart"
}

apply_plan() {
    stalwart-cli --url http://127.0.0.1:8080 --user setup --password "$SETUP_PASSWORD" \
        apply --file "$1"
}

# 1. The first start is in bootstrap mode: submit what the setup wizard would.
if [ -n "$HETZNER_TOKEN" ]; then
    dns='{"@type": "Hetzner", "description": "Hetzner DNS",
          "secret": {"@type": "EnvironmentVariable", "variableName": "HETZNER_TOKEN"}}'
else
    dns='{"@type": "Manual"}'
fi
jq -cn --arg host "$HOST" --arg domain "$DOMAIN" --argjson dns "$dns" \
    '{"@type": "update", object: "Bootstrap", value: {defaultHostname: $host,
      defaultDomain: $domain, requestTlsCertificate: true, generateDkimKeys: true,
      dnsServer: $dns}}' >"${WORK}/bootstrap.ndjson"

log "Configuring Stalwart"
wait_for_stalwart
apply_plan "${WORK}/bootstrap.ndjson"
for i in $(seq 1 30); do [ -e "${CONF}/config.json" ] && break; sleep 1; done
[ -e "${CONF}/config.json" ] || die "the bootstrap did not complete"

# 2. Restart in recovery mode, where no mail is accepted yet, and load the rest.
write_env recovery
systemctl restart stalwart
wait_for_stalwart

{
    jq -cn --arg domain "$DOMAIN" \
        '{"@type": "upsert", object: "Domain", matchOn: ["name"], value: {dom: {name: $domain}}}'
    jq -cn --arg user "$SMTP2GO_USER" \
        '{"@type": "upsert", object: "MtaRoute", matchOn: ["name"], value: {relay: {"@type": "Relay",
          name: "smtp2go", host: "mail.smtp2go.com", port: 587, protocol: "smtp", implicitTls: false,
          authUsername: $user,
          authSecret: {"@type": "EnvironmentVariable", variableName: "SMTP2GO_PASSWORD"}}}}'
    # Mail for other domains goes through SMTP2GO, and its certificate is always checked.
    jq -cn '{"@type": "update", object: "MtaOutboundStrategy", value: {
          route: {match: {"0": {if: "is_local_domain(rcpt_domain)", then: "'"'local'"'"}},
                  else: "'"'smtp2go'"'"},
          tls: {else: "'"'default'"'"}}}'
} >"${WORK}/plan.ndjson"

accounts=$(jq -n --arg pw "$ADMIN_PASSWORD" '{admin: {"@type": "User", name: "admin", domainId: "#dom",
    roles: {"@type": "Admin"}, credentials: {"0": {"@type": "Password", secret: $pw}}}}')
: >"${WORK}/passwords"
for user in $USERS; do
    pw=$(password)
    printf '%s@%s  %s\n' "$user" "$DOMAIN" "$pw" >>"${WORK}/passwords"
    accounts=$(jq --arg name "$user" --arg pw "$pw" '. + {("u-" + $name): {"@type": "User",
        name: $name, domainId: "#dom", credentials: {"0": {"@type": "Password", secret: $pw}}}}' <<<"$accounts")
done
jq -cn --argjson value "$accounts" \
    '{"@type": "upsert", object: "Account", matchOn: ["name"], value: $value}' >>"${WORK}/plan.ndjson"

apply_plan "${WORK}/plan.ndjson"

# 3. Start normally, without the setup administrator.
write_env normal
systemctl restart stalwart
rm -f "${WORK}/bootstrap.ndjson" "${WORK}/plan.ndjson"

# ---- What to do next ---------------------------------------------------------------

{
    echo "Your mail server ${HOST} is set up."
    echo
    echo "Administrator:  https://${HOST}/admin"
    echo "                admin@${DOMAIN}  ${ADMIN_PASSWORD}"
    echo
    echo "Accounts (each person adds theirs in Outwright with address and password):"
    cat "${WORK}/passwords"
    echo
    if [ -n "$HETZNER_TOKEN" ]; then
        echo "1. At your domain registrar, set the nameservers of ${DOMAIN} to:"
        echo "      ${NAMESERVERS:-the ones Hetzner shows for the zone in the Cloud Console}"
        echo "   Stalwart then publishes the rest of the records and gets its certificate."
        if [ -n "$SMTP2GO_ID" ]; then
            echo "2. In SMTP2GO, verify ${DOMAIN} once the nameservers are in place."
        else
            echo "2. In SMTP2GO, add ${DOMAIN} as a sender domain and publish the three CNAME"
            echo "   records it shows in the zone in the Hetzner Cloud Console, then verify."
        fi
    else
        echo "1. Publish the records of the zone file: admin, Domains, ${DOMAIN}, View Zone File."
        echo "   Add an MX record for ${DOMAIN} pointing at ${HOST}, and A/AAAA for ${HOST}."
        echo "2. Set reverse DNS of the server's addresses to ${HOST}."
        echo "3. Open ports 25, 465, 993 and 443, and keep 8080 closed."
        echo "4. In SMTP2GO, add ${DOMAIN} as a sender domain, publish its records and verify."
    fi
    echo
    echo "Then send a test message and check that SMTP2GO's activity list says Delivered."
} >"$OUT"
chmod 600 "$OUT"
rm -f "${WORK}/passwords"

log "Done. Read ${OUT} for the passwords and the next steps."
