#!/bin/ksh

#/* Part of the Maestro sequencer software package.
# * Copyright (C) 2011-2015  Operations division of the Canadian Meteorological Centre
# *                          Environment Canada
# *
# * Maestro is free software; you can redistribute it and/or
# * modify it under the terms of the GNU Lesser General Public
# * License as published by the Free Software Foundation,
# * version 2.1 of the License.
# *
# * Maestro is distributed in the hope that it will be useful,
# * but WITHOUT ANY WARRANTY; without even the implied warranty of
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# * Lesser General Public License for more details.
# *
# * You should have received a copy of the GNU Lesser General Public
# * License along with this library; if not, write to the
# * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# * Boston, MA 02111-1307, USA.
# */

arguments=$*

eval `cclargs $0 \
  -n        ""                    ""                           "[Node ]" \
  -ext      ""                    ""                           "[Extension ]" \
  -v        "0"                   "1"                          "[Verbose             ]" \
  -h        ""                    ""                           "[Display help        ]" \
  ++ $arguments`


[[ $v == 1 ]] && set -x 

# Check for required command line args
if [[ -z "${n}" ]] ; then
  print "Usage: $(basename $0) -n NODE -ext EXTENSION" >&2
  print "\n  Example: $(basename $0) -n main/post_assimcycle/prog/forecast/gem/Sortie -ext +0000001896\n" >&2
  exit 1
fi

# Check for required environment
if [[ -z "${SEQ_EXP_HOME}" ]] ; then
  print "Error: SEQ_EXP_HOME must be set" >&2
  exit 1
fi

# End if no extension is provided
if [[ -z "${ext}" ]] ; then
  exit 0
fi

# Reconstitute the extensions for a node
my_fullnode=${n}.${ext}
if [[ $(basename ${my_fullnode} | grep '\.' | wc -w) -eq 0 ]] ; then return ; fi
my_node=${my_fullnode%%.*}
set -A parent_list $(nodeinfo -n ${my_node} | grep node.loop_parent.name | rev | cut -d '/' -f 1 | rev )
set -A ext_list $(echo ${my_fullnode##*.} | sed 's/\+/ /g')
i=0; loop_args=""
while [[ $i -lt ${#ext_list[*]} ]] ; do
  if [[ -n ${loop_args} ]] ; then loop_args=${loop_args}"," ; fi
  if [[ -n "${parent_list[$i]}" ]] ; then key=${parent_list[$i]} ; else key=$(basename ${my_node}) ; fi
  loop_args=${loop_args}${key}=${ext_list[$i]}
  i=$((i+1))
done
print ${loop_args}
