#!/usr/bin/env bash
# Merge KEY=VALUE lines from a fragment file into target .env (replace existing keys).
set -euo pipefail

TARGET="${1:?target .env path}"
FRAGMENT="${2:?fragment file path}"

touch "$TARGET"
tmp="$(mktemp)"
if [[ -f "$TARGET" ]]; then
  cp "$TARGET" "$tmp"
else
  : > "$tmp"
fi

while IFS= read -r line || [[ -n "$line" ]]; do
  line="${line//$'\r'/}"
  [[ -z "$line" || "$line" =~ ^[[:space:]]*# ]] && continue
  key="${line%%=*}"
  [[ "$key" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] || continue
  grep -v "^${key}=" "$tmp" > "${tmp}.new" || true
  mv "${tmp}.new" "$tmp"
  printf '%s\n' "$line" >> "$tmp"
done < "$FRAGMENT"

if grep -q '^OMNL_FINERACT_USER=' "$tmp" && ! grep -q '^OMNL_FINERACT_USERNAME=' "$tmp"; then
  u="$(grep '^OMNL_FINERACT_USER=' "$tmp" | cut -d= -f2-)"
  printf 'OMNL_FINERACT_USERNAME=%s\n' "$u" >> "$tmp"
fi

mv "$tmp" "$TARGET"
tr -d '\r' <"$TARGET" >"${TARGET}.lf" && mv "${TARGET}.lf" "$TARGET"
chmod 600 "$TARGET"
