#!/bin/bash set +e strip_yaml_comments() { local file=$1 if [[ ! -f "$file" ]]; then echo "File not found: $file" return 1 fi # Filter out lines that are either full-line comments or completely empty sed -i '/^\s*#/d;/^\s*$/d' "$file" if [ $? -eq 0 ]; then echo "Comments stripped successfully in $file" else echo "Failed to strip comments from the file." return 1 fi } download_and_process_config() { local url="https://raw.githubusercontent.com/juanfont/headscale/main/config-example.yaml" local target_dir="/etc/headscale" local target_file="${target_dir}/config-example.yaml" # Create target directory if it does not exist mkdir -p "$target_dir" # Download the file using curl curl -o "$target_file" "$url" if [ $? -eq 0 ]; then echo "Config downloaded successfully to $target_file" # Process the downloaded file to strip comments strip_yaml_comments "$target_file" else echo "Failed to download the config file" return 1 fi } insert_env_placeholders() { local config_file="/etc/headscale/config-example.yaml" if [[ ! -f "$config_file" ]]; then echo "Config file $config_file not found." return 1 fi # Substitute only simple, single-line configuration options sed -i 's|^server_url:.*|server_url: ${SERVER_URL}|' "$config_file" sed -i 's|^listen_addr:.*|listen_addr: ${LISTEN_ADDR}|' "$config_file" sed -i 's|^metrics_listen_addr:.*|metrics_listen_addr: ${METRICS_LISTEN_ADDR}|' "$config_file" sed -i 's|^grpc_listen_addr:.*|grpc_listen_addr: ${GRPC_LISTEN_ADDR}|' "$config_file" sed -i 's|^grpc_allow_insecure:.*|grpc_allow_insecure: ${GRPC_ALLOW_INSECURE}|' "$config_file" sed -i 's|^db_type:.*|db_type: ${DB_TYPE}|' "$config_file" sed -i 's|^db_path:.*|db_path: ${DB_PATH}|' "$config_file" sed -i 's|^acme_url:.*|acme_url: ${ACME_URL}|' "$config_file" sed -i 's|^acme_email:.*|acme_email: ${ACME_EMAIL}|' "$config_file" sed -i 's|^tls_letsencrypt_hostname:.*|tls_letsencrypt_hostname: ${TLS_LETSENCRYPT_HOSTNAME}|' "$config_file" sed -i 's|^tls_letsencrypt_cache_dir:.*|tls_letsencrypt_cache_dir: ${TLS_LETSENCRYPT_CACHE_DIR}|' "$config_file" sed -i 's|^unix_socket:.*|unix_socket: ${UNIX_SOCKET}|' "$config_file" sed -i 's|^unix_socket_permission:.*|unix_socket_permission: ${UNIX_SOCKET_PERMISSION}|' "$config_file" echo "Environment variable placeholders inserted in $config_file" } download_and_process_config insert_env_placeholders