#!/bin/bash
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../" >/dev/null 2>&1 && pwd)"

ENV_FILE="$DIR/.env.override"
touch "$ENV_FILE"
# Read the variable name and var_value from the arguments
var_name="$1"
var_value=$(cat)

# Sanitize var_value to handle special characters
var_value=$(printf '%s' "$var_value")

# Check if .env file exists and contains the specified variable
if grep -q "$var_name=" .env.override; then
    # Replace the existing variable value (handles both macOS and GNU sed)
    if [[ "$OSTYPE" == "darwin"* ]]; then
        sed -i '' "s/$var_name=.*/$var_name=$var_value/" $ENV_FILE
    else
        sed -i "s/$var_name=.*/$var_name=$var_value/" $ENV_FILE
    fi
else
    # Add the variable to the .env file
    printf "\n%s=%s" "$var_name" "$var_value" >> .env.override
fi
