#!/bin/bash

set -e
set -u

attempt=1
maxattempts=60
patience=1
nodename=$(ngcp-nodename)
rc=1

while [[ ${attempt} -le ${maxattempts} ]]; do
  if echo 'quit' | gluster &>/dev/null ; then
    # The gluster brick name can be:
    # 'sp1:/ngcp-data/glusterfs/export' for newly installed system with partitions support
    # 'sp1:/var/lib/glusterfs/export' for upgraded from previous releases (no partitions support)
    brick_name=$(gluster volume status ngcp | awk "/^Brick ${nodename}:/ {print \$2; exit}")
    if [ -z "${brick_name}" ]; then
      continue
    fi

    brick_status=$(gluster volume status ngcp "${brick_name}" detail | awk '/Online/ {print $NF; exit}')
    if [[ "${brick_status}" = "Y" ]]; then
      rc=0
      break
    fi
  fi

  sleep ${patience}
  attempt=$((attempt+1))
done

exit ${rc}
