#!/bin/bash
#
# Copyright 2019 Skycloud Software
#
# Client command wrapper in multiple cluster environment
# Add option --clu=<cluster_name>
# If no option is provided, take action in the default cluster
#
clienttop=`dirname $CB_ENVDIR`
if [[ $CB_ENVDIR != *"/clusters/"* ]]; then
    clusters=`ls $clienttop/clusters | grep -v default`
fi

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

case `basename $0` in
  bchkpnt)
    command=cchkpnt.orig
    ;;
  bkill)
    command=ckill.orig
    ;;
  bmig)
    command=cmig.orig
    ;;
  bpost)
    command=cpost.orig
    ;;
  brestart)
    command=crestart.orig
    ;;
  bsub)
    command=csub.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
else
    cluster=default
fi

if [[ $CB_ENVDIR != *"/clusters/"* ]]; then
    export CB_ENVDIR=$clienttop/clusters/$cluster/etc
fi
exec $command
