#!/bin/sh
#
# Dump environment variables to a file.
#
# This script is intended to be run by the Gitlab Runner, to dump all Gitlab
# variables to the secrets file.
#

# The user can optionally specify the output file
OUTPUT_FILE="${1:-.env}"

# Delete the old file if it exists, and create one with secure permissions
rm -f "${OUTPUT_FILE}"

# Set 'rwx' only for user
umask 077
touch "${OUTPUT_FILE}"

# Dump each exported variable
# According to the current setup:
# DASHBOARDS_ prefix for variables relevant to OpenSearch Dashboards.
# METRICBEAT_ prefix for variables relevant to Metricbeat.
# OPENSEARCH_ prefix for variables relevant to OpenSearch nodes.
while read -r var; do
    echo $var >> "${OUTPUT_FILE}"
done <<- EOF
    $(env | grep -E "^CERTBOT_.*|^DASHBOARDS_.*|^METRICBEAT_.*|^OPENSEARCH_.*")
EOF
