
function addlogprefix {
  ME="`basename -- "$0" .sh`@`hostname`"
  while read LINE
  do
    echo "$ME" "`date "+%F %T.%3N"`" "$LINE"
  done
}

#
# The following functions assume that $PARSET is set.
#

function getkey {
  KEY=$1
  DEFAULT=$2

  # grab the last key matching "^$KEY=", ignoring spaces.
  VALUE=`<$PARSET perl -ne '/^'$KEY'\s*=\s*"?(.*?)"?\s*$/ || next; print "$1\n";' | tail -n 1`

  if [ "$VALUE" == "" ]
  then
    echo "$DEFAULT"
  else
    echo "$VALUE"
  fi
}

function setkey {
  KEY=$1
  VAL=$2

  # In case already there, comment all out to avoid stale warnings. Then append.
  KEYESC=`echo "$KEY" | sed -r -e "s/([\.[])/\\\\\\\\\1/g"`  # escape '.' '[' chars in keys with enough '\'
  sed -i --follow-symlinks -r -e "s/^([[:blank:]]*$KEYESC[[:blank:]]*=)/#\1/g" "$PARSET"
  echo "$KEY = $VAL" >> "$PARSET"
}

COBALT_DATAPRODUCTS="Correlated CoherentStokes IncoherentStokes"

function read_cluster_model {
  # HACK: Search for first cluster, and assume they're all the same. We support only output
  # to a single cluster for now.
  for DP in ${COBALT_DATAPRODUCTS}; do
    CLUSTER_NAME=$(getkey Observation.DataProducts.Output_${DP}.storageClusterName "")
    if [ -n "${CLUSTER_NAME}" ]; then
      break
    fi
  done

  # Hack to derive required properties (cluster model) from cluster name.
  case "${CLUSTER_NAME}" in
    CEP4)
      HEADNODE=head01.cep4.control.lofar
      COMPUTENODES="`ssh $HEADNODE sinfo --responding --states=idle,mixed,alloc --format=%n.cep4,%T --noheader --partition=cobalt --sort=N | fgrep -v ,draining | cut -f1 -d,`"
      if [ -z "$COMPUTENODES" ]; then
        echo "ERROR: Could not obtain list of available CEP4 nodes. Defaulting to all."
        COMPUTENODES="`seq -f "cpu%02.0f.cep4" 1 50`"
      fi

      GLOBALFS_DIR=/data

      #SLURM=true
      SLURM=false # Don't use SLURM for now, let's get it working without it first
      GLOBALFS=true
      DOCKER=false # disabled as outputproc is too slow on docker 1.9.1 (#9522)

      OUTPUTPROC_ROOT="`echo '/opt/outputproc-${LOFAR_TAG}' | docker-template`"
      ;;
    *)
      HEADNODE=lhn001.cep2.lofar
      COMPUTENODES="`seq -f "locus%02.0f" 1 94`"

      SLURM=false
      GLOBALFS=false
      DOCKER=false

      OUTPUTPROC_ROOT="/data/home/lofarsys/production/lofar_cobalt"
      ;;
  esac

  NRCOMPUTENODES=`echo $COMPUTENODES | wc -w`
}
