#!/bin/bash
set -eu

# Check environment variables
reqenv() {
    if [ -z "${!1:-}" ]; then
        echo "Error: environment variable '$1' is not set. check .env file!"
        exit 1
    fi
}
reqenv "CONFIG_DIR"
reqenv "L1_RPC_URL"
reqenv "L1_RPC_KIND"
reqenv "L1_BEACON_URL"
reqenv "L2_CHAIN_ID"

OPTIMISM_PORTAL_PROXY=$(jq -r '.OptimismPortalProxy' /config/deploy.json)
ADDRESS_MANAGER=$(jq -r '.AddressManager' /config/deploy.json)
L1_CROSS_DOMAIN_MESSANGER_PROXY=$(jq -r '.L1CrossDomainMessengerProxy' /config/deploy.json)
L1_STANDARD_BRIDGE_PROXY=$(jq -r '.L1StandardBridgeProxy' /config/deploy.json)
L2_OUTPUT_ORACLE_PROXY=$(jq -r '.L2OutputOracleProxy' /config/deploy.json)

sudo tee "/app/.env" > /dev/null <<EOF
REACT_APP_OPTIMISM_PORTAL_PROXY=$OPTIMISM_PORTAL_PROXY
REACT_APP_ADDRESS_MANAGER=$ADDRESS_MANAGER
REACT_APP_L1_CROSS_DOMAIN_MESSANGER_PROXY=$L1_CROSS_DOMAIN_MESSANGER_PROXY
REACT_APP_L1_STANDARD_BRIDGE_PROXY=$L1_STANDARD_BRIDGE_PROXY
REACT_APP_L2_OUTPUT_ORACLE_PROXY=$L2_OUTPUT_ORACLE_PROXY
REACT_APP_L2_CHAIN_ID=$L2_CHAIN_ID
REACT_APP_L1_CHAIN_ID=$L1_CHAIN_ID
REACT_APP_L2_RPC_URL=$L2_RPC_URL
REACT_APP_L1_RPC_URL=$L1_RPC_URL
REACT_APP_L2_NETWORK_NAME=$L2_CHAIN_NAME
REACT_APP_L2_EXPLORER_URL=$L2_SCAN_URL
REACT_APP_L2_BRIDGE=0x4200000000000000000000000000000000000010
REACT_APP_L1_DAI=0xFF34B3d4Aee8ddCd6F9AFFFB6Fe49bD371b8a357
REACT_APP_L2_DAI=
REACT_APP_L1_USDT=0xaA8E23Fb1079EA71e0a56F48a2aA51851D8433D0
REACT_APP_L2_USDT=
REACT_APP_L1_USDC=0x94a9D9AC8a22534E3FaCa9F4e7F2E2cf85d5E4C8
REACT_APP_L2_USDC=
REACT_APP_L1_wBTC=0x29f2D40B0605204364af54EC677bD022dA425d03
REACT_APP_L2_wBTC=
EOF

cd /app && yarn start