Files
proxmox-mailserver/update_dkim.sh
2025-12-21 22:10:08 -08:00

74 lines
2.0 KiB
Bash
Executable File

#!/bin/bash
# --- Storage Mounts (ZFS Persistence) ---
#mp0: /local-zfs/mail/data,mp=/var/mail
#mp1: /local-zfs/mail/state,mp=/var/mail-state
#mp2: /local-zfs/mail/logs,mp=/var/log/mail
#mp3: /local-zfs/mail/config,mp=/tmp/docker-mailserver
# --- Secrets (Read-Only) ---
#mp4: /root/secrets,mp=/mnt/secrets,ro=1
# --- CONFIGURATION ---
SECRETS_FILE="/root/secrets/mailserver.env"
# Load Secrets
if [ -f "$SECRETS_FILE" ]; then
source "$SECRETS_FILE"
else
echo "Error: Secrets file not found at $SECRETS_FILE"
exit 1
fi
TOKEN="$CF_TOKEN"
ZONE_ID="$CF_ZONE_ID"
DOMAIN="$CF_DOMAIN"
SELECTOR="${CF_SELECTOR:-mail}"
KEY_FILE="/local-zfs/mail/config/opendkim/keys/$DOMAIN/$SELECTOR.txt"
echo "📂 Looking for key at: $KEY_FILE"
if [ ! -f "$KEY_FILE" ]; then
echo "❌ Error: DKIM key file not found!"
exit 1
fi
# --- ROBUST EXTRACTION LOGIC ---
# 1. Cat the file
# 2. Remove newlines to make it one long string (tr -d '\n')
# 3. Extract everything between parentheses (sed ...)
# 4. Remove all double quotes (tr -d '"')
# 5. Remove all spaces/tabs (tr -d '[:space:]') - valid for DKIM records
DKIM_VALUE=$(cat "$KEY_FILE" | tr -d '\n' | sed 's/.*(\(.*\)).*/\1/' | tr -d '"' | tr -d '[:space:]')
# --- DEBUGGING CHECK ---
if [ -z "$DKIM_VALUE" ]; then
echo "❌ Error: Extracted DKIM value is empty. Check the file format."
echo "Raw File Content:"
cat "$KEY_FILE"
exit 1
fi
echo "✅ Extracted Key (First 50 chars): ${DKIM_VALUE:0:50}..."
# --- PUSH TO CLOUDFLARE ---
echo "☁️ Pushing to Cloudflare..."
RESPONSE=$(curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
--data '{
"type": "TXT",
"name": "'"$SELECTOR"'._domainkey",
"content": "'"$DKIM_VALUE"'",
"ttl": 1,
"proxied": false
}')
# Check if curl succeeded
if [[ "$RESPONSE" == *"\"success\":true"* ]]; then
echo "🎉 Success! DKIM record added."
else
echo "❌ Cloudflare Error:"
echo "$RESPONSE"
fi