{{- if .Values.artifactory.catalinaLoggers }}
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ template "artifactory-ha.fullname" . }}-catalina-logger
  labels:
    app: {{ template "artifactory-ha.name" . }}
    chart: {{ template "artifactory-ha.chart" . }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
data:
  tail-log.sh: |
    #!/bin/sh

    LOG_DIR=$1
    LOG_NAME=$2
    PID=

    # Wait for log dir to appear
    while [ ! -d ${LOG_DIR} ]; do
      sleep 1
    done
    sleep 5

    cd ${LOG_DIR}

    LOG_PREFIX=$(echo ${LOG_NAME} | awk -F\. '{print $1}')

    # Find the log to tail
    LOG_FILE=$(ls -1t ./${LOG_PREFIX}.*.log | head -1)

    # echo "Tailing ${LOG_FILE}"
    tail -F ${LOG_FILE} &
    PID=$!

    # Loop forever to see if a new log was created
    while true; do
        # Find the latest log
        NEW_LOG_FILE=$(ls -1t ./${LOG_PREFIX}.*.log | head -1)

        # If a new log file is found, kill old tail and switch to tailing it
        if [ "${LOG_FILE}" != "${NEW_LOG_FILE}" ]; then
            kill -9 ${PID}
            wait $! 2>/dev/null
            LOG_FILE=${NEW_LOG_FILE}

            # echo "Tailing ${LOG_FILE}"
            tail -F ${LOG_FILE} &
            PID=$!
        fi
        sleep 2
    done
{{- end }}
