#!/usr/bin/env bash
set -euo pipefail

rpc_url="${EVERY_CHANNEL_RPC_URL:?set EVERY_CHANNEL_RPC_URL}"
private_key_file="${EVERY_CHANNEL_PRIVATE_KEY_FILE:?set EVERY_CHANNEL_PRIVATE_KEY_FILE}"
quorum="${EVERY_CHANNEL_OBSERVATION_QUORUM:-2}"
out="${EVERY_CHANNEL_OBSERVATION_DEPLOY_OUT:-./test-results/observation-ledger-deploy.json}"

private_key="$(tr -d '\r\n' <"${private_key_file}")"
private_key="${private_key#0x}"

mkdir -p "$(dirname "${out}")"

forge build >/dev/null

owner="$(cast wallet address --private-key "0x${private_key}")"

registry_output="$(forge create contracts/EveryChannelWitnessRegistry.sol:EveryChannelWitnessRegistry \
  --rpc-url "${rpc_url}" \
  --private-key "0x${private_key}" \
  --broadcast \
  --constructor-args "${owner}")"
registry_address="$(printf '%s\n' "${registry_output}" | awk '/Deployed to:/ { print $3 }' | tail -n1)"

ledger_output="$(forge create contracts/EveryChannelObservationLedger.sol:EveryChannelObservationLedger \
  --rpc-url "${rpc_url}" \
  --private-key "0x${private_key}" \
  --broadcast \
  --constructor-args "${registry_address}" "${quorum}")"
ledger_address="$(printf '%s\n' "${ledger_output}" | awk '/Deployed to:/ { print $3 }' | tail -n1)"

if [[ -z "${registry_address}" || -z "${ledger_address}" ]]; then
  echo "failed to deploy contracts" >&2
  exit 1
fi

cat >"${out}" <<EOF
{
  "owner": "${owner}",
  "registry": "${registry_address}",
  "ledger": "${ledger_address}",
  "quorum": ${quorum}
}
EOF

printf '%s\n' "${out}"
