#!/usr/bin/env bash set -euo pipefail # scripts/generate_env.sh # Interactive generator for .env from .env.example # Usage: ./scripts/generate_env.sh [--yes] BASE_DIR="$(cd "$(dirname "$0")/.." && pwd)" EXAMPLE="$BASE_DIR/.env.example" TARGET="$BASE_DIR/.env" confirm=false if [[ "${1:-}" == "--yes" ]]; then confirm=true fi if [[ ! -f "$EXAMPLE" ]]; then echo "Error: .env.example not found at $EXAMPLE" exit 1 fi echo "Generating $TARGET from $EXAMPLE" if [[ -f "$TARGET" && "$confirm" = false ]]; then read -p "$TARGET exists. Overwrite? (y/N): " ans case "$ans" in [Yy]*) ;; *) echo "Aborted"; exit 0;; esac fi # Copy example first cp "$EXAMPLE" "$TARGET" # For each variable in example, prompt the user to keep or change while IFS= read -r line; do if [[ "$line" =~ ^# ]] || [[ -z "$line" ]]; then continue fi key=$(echo "$line" | cut -d= -f1) val=$(echo "$line" | cut -d= -f2-) # Trim key=$(echo "$key" | xargs) val=$(echo "$val" | xargs) current=$(grep -E "^$key=" "$TARGET" || true) current_val="" if [[ -n "$current" ]]; then current_val=$(echo "$current" | cut -d= -f2-) fi if [[ "$confirm" = true ]]; then # non-interactive: keep example defaults or environment overrides env_val="" if [[ -n "${!key:-}" ]]; then env_val="${!key}" fi if [[ -n "$env_val" ]]; then sed -i "s|^$key=.*|$key=$env_val|" "$TARGET" fi continue fi # Interactive mode: prompt user for each variable if read -t 1 -n 0 2>/dev/null; then # stdin is available for reading read -p "$key [$current_val]: " new_val || true else # no stdin available, skip prompting new_val="" fi if [[ -n "$new_val" ]]; then sed -i "s|^$key=.*|$key=$new_val|" "$TARGET" fi done < <(grep -E '^[A-Z0-9_]+=.*' "$EXAMPLE") echo "Written $TARGET" echo "You can re-run this script with --yes to auto-fill from environment variables."