#!/usr/bin/env bash

set -euo pipefail

if [[ $# -ne 1 ]]; then
  echo "usage: $0 <path-to-app.conf>" >&2
  exit 1
fi

config_file=$1

if [[ ! -f "$config_file" ]]; then
  echo "file not found: $config_file" >&2
  exit 1
fi

tmp_file=$(mktemp)
trap 'rm -f "$tmp_file"' EXIT

awk '
function trim(s) {
  sub(/^[[:space:]]+/, "", s)
  sub(/[[:space:]]+$/, "", s)
  return s
}

function starts_with_target_key(line) {
  return line ~ /^[[:space:]]*canton\.parameters\.timeouts\.request-timeout[[:space:]]*=/ ||
         line ~ /^[[:space:]]*canton\.validator-apps([[:space:]]*=|[[:space:]]*\{)/
}

BEGIN {
  skip_block = 0
  depth = 0
}

{
  line = $0

  if (skip_block) {
    opens = gsub(/\{/, "{", line)
    closes = gsub(/\}/, "}", line)
    depth += opens - closes
    if (depth <= 0) {
      skip_block = 0
      depth = 0
    }
    next
  }

  if (line ~ /^[[:space:]]*canton\.parameters\.timeouts\.request-timeout[[:space:]]*=/) {
    next
  }

  if (line ~ /^[[:space:]]*canton\.validator-apps[[:space:]]*\{/) {
    skip_block = 1
    depth = gsub(/\{/, "{", line) - gsub(/\}/, "}", line)
    if (depth <= 0) {
      skip_block = 0
      depth = 0
    }
    next
  }

  if (line ~ /^[[:space:]]*canton\.validator-apps[[:space:]]*=/) {
    next
  }

  print line
}
' "$config_file" > "$tmp_file"

mv "$tmp_file" "$config_file"
