#!/bin/bash
# Description: parse compose file, and modify compose file use new label.
# Usage example:
# change_compose_label docker-compose.yml

function change_compose_label() {
    awk -v service="" '
        {
            if(/^services:\s?$/){
                a=1;
                next;
            }
        }
        {
            if ( a==1 && $0 ~ /^networks:\s?$/){
                exit;
            }
            if( a==1 && match($0,/\s{2}(.+):\s?$/,arr1) && !index(arr1[1], " ")){
                service=arr1[1];
                b=1;
            }
            if( a==1 && b==1 && match($0,/\s+\- node.labels.*/,arr2)) {
                cmd="sed -i ""'\''"NR"s/node.labels.*/node.labels."service" == true/'\''"" '"$1"'"
                print cmd;
                system(cmd);
                b=0;
            }
        }
    ' $1
}
