#!/bin/bash

set -e
set -u
if [ -n "$CERC_SCRIPT_DEBUG" ]; then
  set -x
fi

config_template=$(cat environments/config-template.toml)
target_config="./environments/local.toml"

# Check if faucet key is set
if [ -z "${CERC_FAUCET_KEY:-}" ]; then
  echo "Error: CERC_FAUCET_KEY is not set. Exiting..."
  exit 1
fi

echo "Using laconicd RPC endpoint: $CERC_LACONICD_RPC_ENDPOINT"

FAUCET_CONFIG=$(echo "$config_template" | \
  sed -E "s|REPLACE_WITH_CERC_FAUCET_KEY|${CERC_FAUCET_KEY}|g; \
          s|REPLACE_WITH_CERC_LACONICD_CHAIN_ID|${CERC_LACONICD_CHAIN_ID}|g; \
          s|REPLACE_WITH_CERC_LACONICD_PREFIX|${CERC_LACONICD_PREFIX}|g; \
          s|REPLACE_WITH_CERC_LACONICD_GAS_PRICE|${CERC_LACONICD_GAS_PRICE}|g; \
          s|REPLACE_WITH_CERC_LACONICD_RPC_ENDPOINT|${CERC_LACONICD_RPC_ENDPOINT}|g; ")

echo "$FAUCET_CONFIG" > $target_config
echo "Starting faucet..."
node dist/index.js