Files
family_budget/init-letsencrypt.sh
2025-12-16 11:55:28 +03:00

84 lines
2.7 KiB
Bash
Executable File

#!/bin/bash
if [ -z "$DOMAIN" ]; then
echo "Error: DOMAIN environment variable is not set"
echo "Usage: DOMAIN=yourdomain.com EMAIL=your@email.com ./init-letsencrypt.sh"
exit 1
fi
if [ -z "$EMAIL" ]; then
echo "Error: EMAIL environment variable is not set"
echo "Usage: DOMAIN=yourdomain.com EMAIL=your@email.com ./init-letsencrypt.sh"
exit 1
fi
echo "### Initializing Let's Encrypt for domain: $DOMAIN"
echo "### Email: $EMAIL"
data_path="./certbot"
rsa_key_size=4096
staging=0
if [ -d "$data_path/conf/live/$DOMAIN" ]; then
read -p "Existing certificate found for $DOMAIN. Continue and replace? (y/N) " decision
if [ "$decision" != "Y" ] && [ "$decision" != "y" ]; then
exit
fi
fi
if [ ! -e "$data_path/conf/options-ssl-nginx.conf" ] || [ ! -e "$data_path/conf/ssl-dhparams.pem" ]; then
echo "### Downloading recommended TLS parameters ..."
mkdir -p "$data_path/conf"
curl -s https://raw.githubusercontent.com/certbot/certbot/master/certbot-nginx/certbot_nginx/_internal/tls_configs/options-ssl-nginx.conf > "$data_path/conf/options-ssl-nginx.conf"
curl -s https://raw.githubusercontent.com/certbot/certbot/master/certbot/certbot/ssl-dhparams.pem > "$data_path/conf/ssl-dhparams.pem"
echo
fi
echo "### Creating dummy certificate for $DOMAIN ..."
path="/etc/letsencrypt/live/$DOMAIN"
mkdir -p "$data_path/conf/live/$DOMAIN"
docker compose -f docker-compose.prod.yml run --rm --entrypoint "\
openssl req -x509 -nodes -newkey rsa:$rsa_key_size -days 1\
-keyout '$path/privkey.pem' \
-out '$path/fullchain.pem' \
-subj '/CN=localhost'" certbot
echo
echo "### Starting nginx ..."
docker compose -f docker-compose.prod.yml up --force-recreate -d nginx
echo
echo "### Deleting dummy certificate for $DOMAIN ..."
docker compose -f docker-compose.prod.yml run --rm --entrypoint "\
rm -Rf /etc/letsencrypt/live/$DOMAIN && \
rm -Rf /etc/letsencrypt/archive/$DOMAIN && \
rm -Rf /etc/letsencrypt/renewal/$DOMAIN.conf" certbot
echo
echo "### Requesting Let's Encrypt certificate for $DOMAIN ..."
domain_args="-d $DOMAIN"
case "$staging" in
1) staging_arg="--staging" ;;
*) staging_arg="" ;;
esac
docker compose -f docker-compose.prod.yml run --rm --entrypoint "\
certbot certonly --webroot -w /var/www/certbot \
$staging_arg \
$domain_args \
--email $EMAIL \
--rsa-key-size $rsa_key_size \
--agree-tos \
--force-renewal" certbot
echo
echo "### Enabling SSL configuration..."
envsubst '${DOMAIN}' < nginx/conf.d/app-ssl.conf.template > nginx/conf.d/app-ssl.conf
rm nginx/conf.d/app.conf
echo "### Reloading nginx ..."
docker compose -f docker-compose.prod.yml exec nginx nginx -s reload
echo "### Done! Your site is now secured with HTTPS"