87 lines
2.4 KiB
Bash
87 lines
2.4 KiB
Bash
#!/bin/bash
|
|
set -e
|
|
|
|
# Install required packages
|
|
apk add --no-cache bind-tools
|
|
|
|
# Use environment variables with fallbacks
|
|
DOMAIN=${DOMAIN:-"appflowy.moeny.ai"}
|
|
EMAIL=${EMAIL:-"appflowy-certbot@moeny.ai"}
|
|
BIND_SERVER=${BIND_SERVER:-"ns1.moeny.ai"}
|
|
TSIG_KEY=${TSIG_KEY:-"/tsig.key"} # This will be the path inside the container
|
|
CERTBOT_DIR="/etc/letsencrypt"
|
|
|
|
# Create the auth script with embedded functions
|
|
cat > /tmp/auth.sh << 'EOF'
|
|
#!/bin/sh
|
|
|
|
# Function to add DNS challenge record
|
|
domain="$CERTBOT_DOMAIN"
|
|
token="$CERTBOT_VALIDATION"
|
|
|
|
echo "Adding DNS challenge for $domain with token $token"
|
|
nsupdate -k "/tsig.key" << NSUPDATE
|
|
server $BIND_SERVER
|
|
update add _acme-challenge.$domain. 300 IN TXT "$token"
|
|
send
|
|
NSUPDATE
|
|
|
|
# Wait for DNS propagation
|
|
echo "Waiting 30 seconds for DNS propagation..."
|
|
sleep 30
|
|
|
|
# Verify the record
|
|
echo "Verifying DNS record..."
|
|
if dig +short @$BIND_SERVER TXT _acme-challenge.$domain | grep -q "$token"; then
|
|
echo "DNS challenge record verified successfully"
|
|
exit 0
|
|
else
|
|
echo "ERROR: DNS challenge record not found or incorrect"
|
|
exit 1
|
|
fi
|
|
EOF
|
|
chmod +x /tmp/auth.sh
|
|
|
|
# Create cleanup script with embedded function
|
|
cat > /tmp/cleanup.sh << 'EOF'
|
|
#!/bin/sh
|
|
|
|
domain="$CERTBOT_DOMAIN"
|
|
echo "Removing DNS challenge for $domain"
|
|
nsupdate -k "/tsig.key" << NSUPDATE
|
|
server $BIND_SERVER
|
|
update delete _acme-challenge.$domain. TXT
|
|
send
|
|
NSUPDATE
|
|
EOF
|
|
chmod +x /tmp/cleanup.sh
|
|
|
|
# Check if certificate already exists
|
|
if [ -d "/etc/letsencrypt/live/$DOMAIN" ]; then
|
|
echo "Certificate exists, attempting renewal..."
|
|
certbot renew \
|
|
--manual \
|
|
--preferred-challenges dns \
|
|
--manual-auth-hook /tmp/auth.sh \
|
|
--manual-cleanup-hook /tmp/cleanup.sh \
|
|
--deploy-hook "touch /etc/letsencrypt/deploy-hook-triggered" \
|
|
--force-renewal
|
|
else
|
|
echo "No certificate found, performing initial certificate request..."
|
|
certbot certonly \
|
|
--manual \
|
|
--preferred-challenges dns \
|
|
--manual-auth-hook /tmp/auth.sh \
|
|
--manual-cleanup-hook /tmp/cleanup.sh \
|
|
--deploy-hook "touch /etc/letsencrypt/deploy-hook-triggered" \
|
|
-d "$DOMAIN" \
|
|
--email "$EMAIL" \
|
|
--agree-tos \
|
|
--non-interactive
|
|
fi
|
|
|
|
# Clean up temporary scripts
|
|
rm -f /tmp/auth.sh /tmp/cleanup.sh
|
|
|
|
echo "Certificate operation completed. Check /etc/letsencrypt/deploy-hook-triggered for successful deployment."
|