#!/bin/bash

# Update Environment Variables
# Helper script to update specific environment variables in .env file

set -e

ENV_FILE=".env"

if [ ! -f "$ENV_FILE" ]; then
    echo "Creating .env file from template..."
    if [ -f .env.template ]; then
        cp .env.template "$ENV_FILE"
    else
        touch "$ENV_FILE"
    fi
fi

# Function to update or add variable
update_var() {
    local var_name=$1
    local var_value=$2
    
    if grep -q "^${var_name}=" "$ENV_FILE"; then
        # Update existing variable
        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
        echo "Updated $var_name"
    else
        # Add new variable
        echo "${var_name}=${var_value}" >> "$ENV_FILE"
        echo "Added $var_name"
    fi
}

# Update the provided variables (use placeholders; set real values in .env and never commit).
if [ ! -z "$1" ] && [ "$1" == "update" ]; then
    update_var "ETHEREUM_MAINNET_RPC" "https://mainnet.infura.io/v3/<INFURA_PROJECT_ID>"
    update_var "RPC_URL_138" "http://192.168.11.211:8545"
    update_var "ETHERSCAN_API_KEY" "<YOUR_ETHERSCAN_API_KEY>"
    update_var "INFURA_PROJECT_ID" "<YOUR_INFURA_PROJECT_ID>"
    update_var "INFURA_PROJECT_SECRET" "<YOUR_INFURA_PROJECT_SECRET>"
    echo ""
    echo "✓ Environment variables updated with placeholders"
    echo "  Set real values in .env (INFURA_PROJECT_ID, INFURA_PROJECT_SECRET, ETHERSCAN_API_KEY); never commit secrets."
    echo ""
    echo "Run: ./scripts/deployment/check-env-requirements.sh to verify"
else
    echo "Usage: $0 update"
    echo ""
    echo "This will set placeholders for:"
    echo "  - ETHEREUM_MAINNET_RPC (Infura), RPC_URL_138, ETHERSCAN_API_KEY"
    echo "  - INFURA_PROJECT_ID, INFURA_PROJECT_SECRET (for Infura RPC + Basic Auth)"
fi

