#!/bin/bash
#
# sccl_node
#
# Aufruf:
#
# sccl_node [-v] [-m] [-c|-s|-t|-u] [<node>]
#
# Infos des Knoten <node> abfragen
#   -c: check connections to all nodes
#   -v: Version
#   -m: Master
#   -s: Status - R (Running), B (Booting), D (Down), I (DIsabled), S (Starting/Stopping package)
#   -t: Time
#   -u: Status != B | S
#
########################################################################################
#
if [[ "$1" = "-u" && ! -f /etc/sccl/sccl.conf ]]; then
  echo 'OK'
  exit 0
fi
#
. $(dirname $0)/globals.settings
#
unset ASK
while getopts cmvstu? op; do
  case "$op" in
   c) ASK="c";;
   v) ASK="$op$ASK";;
   m) ASK="$op$ASK";;
   s) ASK="s";;
   t) ASK="t";;
   u) ASK="u";;
   ?) echo "usage: $MYPRG [-v] [-m] [-s] [-c|-t|-u] [<node>]"
      exit 1;;
  esac
done
#
shift $(( $OPTIND - 1))
#
# ist [<node>] angegeben? wenn ja, dann sccl_node auf $1 ausfuehren
#
NODE=$(tr '[:upper:]' '[:lower:]' <<<$1)
NODE=${NODE:-$THISHOSTNAME}
#
if [[ "$1" != "THISNODE" && ( -n "$1" || $ASK =~ "m" ) ]]; then
  readnode $NODE "sccl_node.s2w?ask=$ASK"
elif [[ "$ASK" =~ "c" ]]; then
  for i in $NODES; do
    ret=$(readnode $i "sccl_node.s2w?ask=v")
    [[ -z "$ret" ]] && echo "Warning: $THISHOSTNAME can't connect to $i"
  done
else
  if [[ -f /etc/sccl/capwd.dat && -f /etc/sccl/certs/private/${CLUSTER}-cakey.pem ]]; then
    SCCLMASTER=M
  else
    unset SCCLMASTER
  fi
  if [[ -z "$ASK" ]]; then
    echo "Nodename: $THISHOSTNAME
Version: $SCCLVERSION
Master:  $SCCLMASTER"
  elif [[ $ASK =~ "u" ]]; then
    if [[ -f "$LOCKDIR/node.BOOTING" ]]; then
      echo 'NOT OK'
      exit 1
    elif [[ $(find "$LOCKDIR" -name "*_progress" | wc -l) -gt 0 ]]; then
      if grep -qE ' starting$| stopping$| executing$' $LOCKDIR/*_progress; then
        echo 'NOT OK'
        exit 1
      else
        echo 'OK'
      fi
    else
      echo 'OK'
    fi
  elif [[ $ASK =~ "t" ]]; then
    date '+%s'
  elif [[ $ASK =~ "s" ]]; then
    if [[ $(find "$LOCKDIR" -name "*$PROGRESSEXTENSION" | wc -l) -gt 0 ]]; then
      echo 'S'
    elif [[ -f "$LOCKDIR"/node.BOOTING ]]; then
      echo 'B'
    elif [[ -f "$LOCKDIR"/node.DISABLED ]]; then
      echo 'I'
    elif [[ -f "$LOCKDIR/node.STOPPED" ]]; then
      echo 'D'
    else
      echo 'R'
    fi
  else
    unset OUT
    if [[ $ASK =~ "v" ]]; then
      OUT="$SCCLVERSION"
    fi
    if [[ $ASK =~ "m" ]]; then
      OUT="$OUT${OUT/*/ }$SCCLMASTER"
    fi
    echo "$OUT"
  fi
fi
