---
apiVersion: v1
kind: ConfigMap
metadata:
  name: zk-script-configmap
data:
  start-zk.sh: |
    HOST=`hostname -s`
    DOMAIN=`hostname -d`
    if [[ $HOST =~ (.*)-([0-9]+)$ ]]; then
        NAME=${BASH_REMATCH[1]}
        ORD=${BASH_REMATCH[2]}
    else
        echo "Fialed to parse name and ordinal of Pod"
        exit 1
    fi

    function list_servers() {
      for (( i=1; i<=$1; i++ ))
      do
          echo "server.$i=$NAME-$((i-1)).$DOMAIN:2888:3888"
      done
    }

    # `NODE_COUNT` need to match with `replicas` in `zk-statefulset.yaml`
    NODE_COUNT=3
    export ZOO_MY_ID=$((ORD+1))
    export ZOO_SERVERS=`list_servers $NODE_COUNT`
    /docker-entrypoint.sh
    zkServer.sh start-foreground
  
  liveness-check.sh: |
    echo ruok | nc localhost 2181 | grep imok
    
  readiness-check.sh: |
    RETRY=12
    if nslookup $(hostname -f | sed -e 's/default.svc.cluster.local//') ; then
      rm /tmp/dns-check.log
      echo stat | nc localhost 2181 | grep Zxid
    elif [[ $(wc -l </tmp/readiness-check.log) -lt ${RETRY} ]]; then
      echo 'DNS not ready' >> /tmp/dns-check.log
    else
      echo "retry reach ${RETRY}" >> /tmp/dns-check.log
      exit 1
    fi

