#!/bin/bash
set -e

# Update package lists
apt-get update || { echo "Failed to update package lists"; exit 1; }

# Install certbot and the Nginx plugin
apt-get install -y certbot python3-certbot-nginx || { echo "Failed to install certbot"; exit 1; }

# Backup Nginx configuration
BACKUP_DIR="/etc/nginx/backup"
BACKUP_DATE=$(date +%F)
mkdir -p "$BACKUP_DIR"
cp -r /etc/nginx/sites-available "$BACKUP_DIR/sites-available-$BACKUP_DATE" || echo "Warning: Could not backup Nginx config"

# Obtain certificates for all domains and configure Nginx automatically
certbot --nginx -n \
  -d 2weekmail.fyi \
  -d mail.2weekmail.fyi \
  -d webmail.2weekmail.fyi \
  -d admin.2weekmail.fyi \
  -d api.2weekmail.fyi \
  --agree-tos \
  --email admin@2weekmail.fyi || { echo "Failed to obtain certificates"; exit 1; }

echo "Testing certificate renewal process..."
certbot renew --dry-run || { echo "Certificate renewal test failed"; exit 1; }

# Restart the mail server to use the new certificates
if docker ps -a | grep -q mailserver_postfix; then
    docker restart mailserver_postfix || { echo "Failed to restart mailserver_postfix"; exit 1; }
else
    echo "Warning: mailserver_postfix container not found"
fi

mkdir -p /etc/letsencrypt/renewal-hooks/post/
cat > /etc/letsencrypt/renewal-hooks/post/restart-services.sh << 'EOF'
#!/bin/bash
systemctl reload nginx
docker restart mailserver_postfix
EOF
chmod +x /etc/letsencrypt/renewal-hooks/post/restart-services.sh


# Set up auto-renewal cron job that restarts both Nginx and the mail server
CRON_JOB="0 3 * * 1 certbot renew --quiet"
(crontab -l 2>/dev/null | grep -v "certbot renew"; echo "$CRON_JOB") | crontab - || { 
    echo "Failed to set up cron job. Adding it manually..."; 
    echo "$CRON_JOB" | crontab -; 
}

echo "✅ SSL certificates have been set up for all domains."
echo "✅ Nginx has been configured to use these certificates."
echo "✅ The mail server has been restarted to use the new certificates."
echo "✅ A cron job has been added to automatically renew certificates and restart services."
