#!/bin/bash

FULL_SR_STATUS=$(python /hana/shared/$SAPSYSTEMNAME/exe/linuxppc64/hdb/python_support/systemReplicationStatus.py 2>/dev/null); srRc=$?

case $srRc in
  10) sr_state="No HANA System Replication";show_detail=0;;
  11) sr_state="Error"                     ;show_detail=0;;
  12) sr_state="Unknown"                   ;show_detail=0;;
  13) sr_state="Initializing"              ;show_detail=1;;
  14) sr_state="Syncing"                   ;show_detail=1;;
  15) sr_state="Active (all services in sync)"  ;show_detail=1;;
  *)  echo "Unknown Status"                ;show_detail=1;;
esac

if [ "$show_detail" = "1" ]; then
  sr_state_detail=$(gawk -F '|' \
  'function ltrim(s) { sub(/^[ \t\r\n]+/, "", s); return s }
  function rtrim(s) { sub(/[ \t\r\n]+$/, "", s); return s }
  function trim(s)  { return rtrim(ltrim(s)); }

  /^\|/ && NR>3 {
    if ( out != "" ) { out=out "," }
    state=trim($14)
    if ( state != "ACTIVE" ) {
        out=out trim($4) ":"
        out=out state "(" trim($15) ")" }}
  END { if ( out == "" ) {
    print "all services in sync"
  } else {
    print out }}' <<< "$FULL_SR_STATUS")

  echo "$sr_state: $sr_state_detail"
else
  echo "$sr_state"
fi
