#!/bin/bash
#
# Copyright 2019 Skycloud Software
# 
# Client command wrapper in multiple cluster environment
# Add option --clu=<cluster_name>
# If no option is provided, list information from all clusters
#
clienttop=`dirname $CB_ENVDIR`
clusters=`ls $clienttop/clusters | grep -v default`

function validcluster() {
   for c in $clusters; do
      if [ $1 == $c ]; then
          return 1
      fi
   done
   return 0
}

case `basename $0` in
  bhosts)
    command=chosts.orig
    ;;
  bjobs)
    command=cjobs.orig
    ;;
  bpeek)
    command=cview.orig
    ;;
  bread)
    command=cread.orig
    ;;
  *)
    command=$0.orig
    ;;
esac

while [ $# != '0' ]; do
  case $1 in
  *=*) optarg=`expr "X$1" : '[^=]*=\(.*\)'` ;;
  *)  optarg=no ;;
  esac

  case $1 in
  --clu=*)
        cluster=$optarg
        ;;
  *)
        command="$command $1"
        ;;
  esac
  shift
done

if [ ! -z $cluster ]; then
    validcluster $cluster
    valid=$?
    if [ $valid == 0 ]; then
        echo Invalid cluster name: $cluster
        exit 1
    fi

    export CB_ENVDIR=$clienttop/clusters/$cluster/etc
    exec $command
else
    for cluster in $clusters; do
        export CB_ENVDIR=$clienttop/clusters/$cluster/etc
        echo Cluster: $cluster
        $command
    done
fi
