#!/bin/bash RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[1;33m' CYAN='\033[0;36m' NC='\033[0m' # No Color echo -e "${CYAN}==========================================${NC}" echo -e "${CYAN} Automated SSL Certificate Setup ${NC}" echo -e "${CYAN}==========================================${NC}\n" # 1. Load variables from .env if [ ! -f ".env" ]; then echo -e "${RED}[ERROR] .env file not found. Skipping SSL setup.${NC}" exit 1 fi source .env # 2. Check if HTTPS is being used if [[ ! "$GITLAB_EXTERNAL_URL" == https://* ]]; then echo -e "${YELLOW}[INFO] GITLAB_EXTERNAL_URL is not using HTTPS. Skipping custom SSL setup.${NC}" exit 0 fi # 3. Extract the clean domain name from the URL (e.g., git.example.com) DOMAIN=$(echo "$GITLAB_EXTERNAL_URL" | sed -e 's|^[^/]*//||' -e 's|/.*$||') if [ -z "$DOMAIN" ]; then echo -e "${RED}[ERROR] Could not extract domain from GITLAB_EXTERNAL_URL.${NC}" exit 1 fi # 4. Check if the custom-ssl folder has the required certificates if [ ! -f "./custom-ssl/fullchain.pem" ] || [ ! -f "./custom-ssl/privatekey.pem" ]; then echo -e "${YELLOW}[INFO] No custom certificates found in ./custom-ssl/ (missing fullchain.pem or privatekey.pem).${NC}" echo -e "Skipping automated SSL setup." exit 0 fi echo -e "${GREEN}[OK] Custom certificates found for $DOMAIN.${NC}" # 5. Determine the config directory based on GITLAB_HOME SSL_DIR="${GITLAB_HOME:-./gitlab-data}/config/ssl" # 6. Create the SSL directory if it doesn't exist mkdir -p "$SSL_DIR" # 7. Copy and rename the files to match GitLab's strict requirements echo -e "Copying and renaming certificates..." cp ./custom-ssl/fullchain.pem "$SSL_DIR/$DOMAIN.crt" cp ./custom-ssl/privatekey.pem "$SSL_DIR/$DOMAIN.key" # 8. Set the exact required security permissions chmod 644 "$SSL_DIR/$DOMAIN.crt" chmod 600 "$SSL_DIR/$DOMAIN.key" echo -e "${GREEN}[OK] Certificates copied to $SSL_DIR as $DOMAIN.crt and $DOMAIN.key${NC}" echo -e "${GREEN}[OK] Strict file permissions applied.${NC}" # 9. Force disable internal Let's Encrypt to prevent overwriting if grep -q "^LETSENCRYPT_ENABLE=true" .env; then echo -e "${YELLOW}[WARNING] LETSENCRYPT_ENABLE is set to true in .env. Disabling it to prevent conflicts with your custom CDN certs...${NC}" sed -i 's/^LETSENCRYPT_ENABLE=true/LETSENCRYPT_ENABLE=false/' .env echo -e "${GREEN}[OK] LETSENCRYPT_ENABLE forcefully set to false.${NC}" fi echo -e "\n${GREEN}[SUCCESS] Custom SSL setup complete!${NC}\n"