#!/usr/bin/env bash
# 将 server/.env.example 中「server/.env 尚未出现的 KEY=」追加到 .env，不覆盖已有配置。
# 供 pull-and-restart / restart 调用，实现服务器零手动改 .env。
set +e
ROOT="${1:-}"
if [ -z "$ROOT" ]; then
  ROOT="$(cd "$(dirname "$0")/.." && pwd)"
fi
ENVF="$ROOT/server/.env"
EX="$ROOT/server/.env.example"
[ -f "$EX" ] || exit 0
[ -f "$ENVF" ] || exit 0

while IFS= read -r raw || [ -n "$raw" ]; do
  line="${raw#"${raw%%[![:space:]]*}"}"
  line="${line%"${line##*[![:space:]]}"}"
  case "$line" in
    \#*|'') continue ;;
  esac
  case "$line" in
    [A-Za-z_][A-Za-z0-9_]*=*)
      key="${line%%=*}"
      if ! grep -qE "^[[:space:]]*${key}=" "$ENVF" 2>/dev/null; then
        printf '\n# auto from .env.example (%s)\n%s\n' "$(date +%Y-%m-%d)" "$line" >> "$ENVF"
        echo "merge-server-env: 已追加 $key -> server/.env" >&2
      fi
      ;;
  esac
done < "$EX"
exit 0
