#!/usr/bin/env bash
# GridAdmin Namespace Init task
# Description: boostraps a namespace in OIO-SDS

TASK="NS_INIT"
source $(dirname $0)/oio-ga-tools-logger

timeout=30

while getopts ":z:n:" opt; do
  case $opt in
    z)
      ZK_URLS=$OPTARG
      ;;
    n)
      NS=$OPTARG
      ;;
    \?)
      log "WARN" "Invalid option provided -$OPTARG"
      exit 1
      ;;
    :)
      log "WARN" "Option -$OPTARG requires argument."
      exit 1
      ;;
  esac
done

if [ -z "$NS" ] || [ -z "$ZK_URLS" ]; then
    log "ERROR" "Not enough arguments provided. Aborting."
    exit 1
fi

# TODO: implement zk checks

if ! [ -x "$(command -v nc)" ]; then
	log "ERROR" "Netcat not found."
	exit 1
fi

while true; do
	((timeout=timeout-1))
	f=true
	for url in ${ZK_URLS//,/ }; do
		if ! [ "$(echo ruok | nc ${url/:/ })" = "imok" ]; then
		 	f=false
		fi
  done

	if [ $timeout -eq 0 ]; then
		log "ERROR" "Zookeeper connection could not be established (TIMEOUT)"
		exit 1
	fi

  if [ "$f" = true ]; then
		/usr/bin/zk-bootstrap.py $NS
		break
	fi

	sleep 1
done

/usr/bin/oio-cluster $NS
/usr/bin/oio-meta0-init -O NbReplicas=3 $NS
log "INFO" "Namespace $NS boostrap complete"
exit 0
