Files
proxmox-mailserver/sync_mail_certs.sh
2026-01-02 17:20:11 -08:00

46 lines
1.4 KiB
Bash
Executable File

#!/bin/bash
# --- CONFIGURATION ---
ENV_FILE="/root/secrets/redis.env"
if [ -f "$ENV_FILE" ]; then
export $(grep -v '^#' "$ENV_FILE" | xargs)
export REDISCLI_AUTH="$REDIS_PASSWORD"
else
echo "ERROR: Secret file $ENV_FILE not found."
exit 1
fi
REDIS_HOST="192.168.0.120"
REDIS_PORT="6379"
REDIS_DB="2"
DEST_DIR="/local-zfs/mail/config/ssl"
DOMAIN="mail.poppyglen.cc"
# Key paths in Redis
CERT_KEY="caddy/certificates/acme-v02.api.letsencrypt.org-directory/$DOMAIN/$DOMAIN.crt"
PRIV_KEY="caddy/certificates/acme-v02.api.letsencrypt.org-directory/$DOMAIN/$DOMAIN.key"
mkdir -p "$DEST_DIR"
echo "Fetching and decoding certs from Redis..."
# Logic:
# 1. Get raw JSON from Redis
# 2. Use jq to get the "value" field
# 3. Use base64 -d to turn that string back into a PEM file
redis-cli -h "$REDIS_HOST" -p "$REDIS_PORT" -n "$REDIS_DB" --raw GET "$CERT_KEY" | jq -r '.value' | base64 -d > "$DEST_DIR/cert.pem"
redis-cli -h "$REDIS_HOST" -p "$REDIS_PORT" -n "$REDIS_DB" --raw GET "$PRIV_KEY" | jq -r '.value' | base64 -d > "$DEST_DIR/key.pem"
# --- VERIFICATION ---
if openssl x509 -in "$DEST_DIR/cert.pem" -noout > /dev/null 2>&1; then
echo "Success! Certificate is valid."
chmod 644 "$DEST_DIR/cert.pem" "$DEST_DIR/key.pem"
# Reload Mail Services
# pct exec 124 -- postfix reload
# pct exec 124 -- dovecot reload
else
echo "ERROR: Extraction failed. The resulting cert.pem is not a valid certificate."
exit 1
fi