#!/usr/bin/env bash

# This script fixes the log4j CVE-2021-44228 vulnerability for instances using Elasticsearch 5.x

yq() {
  docker run --rm -i -v "${PWD}:/workdir" --user "$UID" mikefarah/yq:4 "$@"
}

config() {
  SERVICE="$(yq eval '.services.*.image | select(. == "elasticsearch:5*") | path | .[-2]' docker-compose.yml)"
  if [ -z "$SERVICE" ]; then
    echo "No Elasticsearch 5 image found in docker-compose.yml"
    exit 0
  fi
}

add_var() {
  HAS_OPTS="$(yq eval ".services.$SERVICE.environment | .[] | select(. == \"ES_JAVA_OPTS*\")" docker-compose.yml)"
  if [ -z "$HAS_OPTS" ]; then
    yq -i eval ".services.$SERVICE.environment += \"ES_JAVA_OPTS=-Dlog4j2.formatMsgNoLookups=true\"" docker-compose.yml
  else
    yq -i eval "(.services.$SERVICE.environment | .[] | select(. == \"ES_JAVA_OPTS*\")) += \" -Dlog4j2.formatMsgNoLookups=true\"" docker-compose.yml
  fi
}

proceed()
{
  config
  add_var
}

proceed "$@"
