#!/usr/bin/env bash set -euo pipefail script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" repo_root="$(cd "${script_dir}/.." && pwd)" env_file="${repo_root}/.env.devprod" template_file="${repo_root}/.env.example" dry_run="0" backup_mode="1" usage() { cat < Target env file (default: .env.devprod) --template-file Source template file (default: .env.example) --dry-run Print missing keys without modifying files --no-backup Do not create a timestamped backup before writing -h, --help Show this help USAGE } while [[ $# -gt 0 ]]; do case "$1" in --env-file) env_file="${2:-}" shift 2 ;; --env-file=*) env_file="${1#*=}" shift ;; --template-file) template_file="${2:-}" shift 2 ;; --template-file=*) template_file="${1#*=}" shift ;; --dry-run) dry_run="1" shift ;; --no-backup) backup_mode="0" shift ;; -h|--help) usage exit 0 ;; *) echo "Unknown option: $1" usage exit 1 ;; esac done if [[ "${env_file}" != /* ]]; then env_file="${repo_root}/${env_file}" fi if [[ "${template_file}" != /* ]]; then template_file="${repo_root}/${template_file}" fi if [[ ! -f "${template_file}" ]]; then echo "Missing template file: ${template_file}" exit 1 fi if [[ ! -f "${env_file}" ]]; then echo "Missing env file: ${env_file}" exit 1 fi key_exists() { local key="$1" grep -qE "^${key}=" "${env_file}" } missing_keys=() missing_lines=() while IFS= read -r line || [[ -n "${line}" ]]; do [[ -z "${line}" ]] && continue [[ "${line}" == \#* ]] && continue [[ "${line}" =~ ^[[:space:]]*# ]] && continue [[ "${line}" =~ ^[A-Za-z_][A-Za-z0-9_]*= ]] || continue key="${line%%=*}" if ! key_exists "${key}"; then missing_keys+=("${key}") missing_lines+=("${line}") fi done < "${template_file}" if [[ "${#missing_keys[@]}" -eq 0 ]]; then echo "No missing env keys found in ${env_file} (template: ${template_file})." exit 0 fi if [[ "${dry_run}" == "1" ]]; then echo "Missing keys in ${env_file}:" printf ' %s\n' "${missing_keys[@]}" echo "Dry run only; no file changes made." exit 0 fi if [[ "${backup_mode}" == "1" ]]; then backup_path="${env_file}.bak.$(date +%Y%m%d%H%M%S)" cp "${env_file}" "${backup_path}" echo "Backup created: ${backup_path}" fi { echo echo "# Added automatically from ${template_file##*/} on $(date -u +%Y-%m-%dT%H:%M:%SZ)" for line in "${missing_lines[@]}"; do echo "${line}" done } >> "${env_file}" echo "Added ${#missing_keys[@]} missing env key(s) to ${env_file}:" printf ' %s\n' "${missing_keys[@]}"