mnemo_cards/tools/ssl/setup_ssl.sh

115 lines
3 KiB
Bash
Raw Normal View History

2025-12-02 23:28:12 +00:00
#!/bin/bash
# SSL Certificate Setup Script for All Mnemo Cards Domains
# Usage: ./setup_ssl.sh
set -e
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Function to print colored output
print_status() {
echo -e "${GREEN}[INFO]${NC} $1"
}
print_warning() {
echo -e "${YELLOW}[WARNING]${NC} $1"
}
print_error() {
echo -e "${RED}[ERROR]${NC} $1"
}
print_success() {
echo -e "${GREEN}[SUCCESS]${NC} $1"
}
echo "🔐 Setting up SSL certificates for all Mnemo Cards domains..."
# Check if running as root
if [ "$EUID" -ne 0 ]; then
print_error "This script must be run as root (sudo)"
exit 1
fi
# Email for Let's Encrypt (can be overridden)
LETSENCRYPT_EMAIL="${LETSENCRYPT_EMAIL:-admin@mnemo-cards.online}"
# Domains to set up certificates for
DOMAINS=(
"mnemo-cards.online"
"api.mnemo-cards.online"
"admin.mnemo-cards.online"
"code.mnemo-cards.online"
"vscode.mnemo-cards.online"
)
# Check if certbot is installed
if ! command -v certbot &> /dev/null; then
print_status "Installing certbot..."
apt update
apt install -y certbot
print_success "Certbot installed"
fi
# Stop nginx temporarily for certificate issuance
print_warning "Stopping nginx for certificate issuance..."
systemctl stop nginx 2>/dev/null || true
# Get certificates for all domains
for domain in "${DOMAINS[@]}"; do
if [ -d "/etc/letsencrypt/live/$domain" ]; then
print_success "Certificate already exists for $domain"
else
print_status "Obtaining certificate for $domain..."
if certbot certonly --standalone -d "$domain" --non-interactive --agree-tos --email "$LETSENCRYPT_EMAIL"; then
print_success "Certificate obtained for $domain"
else
print_error "Failed to obtain certificate for $domain"
fi
fi
done
# Start nginx again
print_status "Starting nginx..."
systemctl start nginx 2>/dev/null || true
# Set up automatic renewal cron job
print_status "Setting up automatic certificate renewal..."
CRON_JOB="0 12 * * * /usr/bin/certbot renew --quiet --post-hook \"systemctl reload nginx\""
# Check if cron job already exists
if ! crontab -l 2>/dev/null | grep -q "certbot renew"; then
# Add cron job
(crontab -l 2>/dev/null; echo "$CRON_JOB") | crontab -
print_success "Automatic renewal cron job added"
else
print_success "Automatic renewal cron job already exists"
fi
# Test renewal
print_status "Testing certificate renewal..."
if certbot renew --dry-run; then
print_success "Certificate renewal test passed"
else
print_warning "Certificate renewal test failed - check configuration"
fi
echo ""
print_success "SSL certificate setup completed!"
echo ""
echo "📋 Summary:"
echo "- Certificates obtained for all domains"
echo "- Automatic renewal configured"
echo "- Nginx restarted and configured"
echo ""
echo "🔍 Run './check_ssl.sh' to verify certificate status"
echo "🔄 Certificates will auto-renew before expiration"