#!/bin/bash
#
# This is an example. DO NOT SOURCE IT !

function enable_log_collection() {
    SERVICE=$(sed -n "/^services/,/^networks/p" $1 | grep -oP '^\s{2}\w+' | grep -Ev "nginx" |sort | uniq| xargs)
    sed -i -r '/^\s{4}logging:/,/^### SVC:.*:<<</{/^### SVC:.*:<<</!d}' $1
    for svc in ${SERVICE[@]}; do
cat >/tmp/enable_log_collection.tmp<<EOF
    logging:
      driver: "syslog"
      options:
        syslog-address: "udp://logserver:55514"
        syslog-format: "rfc3164"
        tag: "${svc}"

EOF
        line_num=$(($(sed -n "/### SVC:${svc}:<<</=" $1)-1))
        sed -i -r "/^services/,/^networks/{
            /^### SVC:${svc}:>>>/,/^### SVC:${svc}:<<</ {
                ${line_num} r /tmp/enable_log_collection.tmp
        }}" $1
        sed -i -r "/^services/,/^networks/{
            /^### SVC:${svc}:>>>/,/^### SVC:${svc}:<<</ {
                /^$/ d
        }}" $1
    done
}

enable_log_collection $@
