---
apiVersion: v1
kind: ConfigMap
metadata:
  name: onos-config-scripts
  labels:
    app: onos
    chart: "{{ .Chart.Name }}-{{ .Chart.Version }}"
    release: "{{ .Release.Name }}"
    heritage: "{{ .Release.Service }}"
data:
  onos-setter: |
    #!/bin/sh
    while true
    set -e -x
    REPLICAS=$(kubectl -n $NAMESPACE get --no-headers sts -lapp=$APP_LABEL -o custom-columns=':.spec.replicas')

    do
      echo 'Checking Pod: Running'
      RUNNING_POD=$(kubectl -n $NAMESPACE get --no-headers pods -lapp=$APP_LABEL | grep Running | wc -l)
      READY_POD=$(kubectl -n $NAMESPACE get --no-headers pods -lapp=$APP_LABEL -o custom-columns=':.status.containerStatuses[*].ready' | grep true | wc -l)
      if [ $REPLICAS -eq $RUNNING_POD ] && [ $REPLICAS -eq $READY_POD ]; then
        echo 'Checking Devices'
        DEVICE_COUNT=$(curl -s -u $USER:$PASSWD -X GET --header 'Accept: application/json' $NETCFG_URL | jq -r '.devices' | jq length)
        if [ $DEVICE_COUNT = 0 ]; then
            curl -v -u $USER:$PASSWD -X POST -H 'Content-Type: application/json' $NETCFG_URL -d@$CFG_FOLDER/$CFG_FILE
        fi
      fi

      sleep 30s
    done

  onos-config: |
    #!/bin/sh
    set -e -x
    rm -rf $CFG_REPO
    git clone https://$USER:$PASSWD@$CFG_SERVER/$CFG_REPO

    if [ ! -z $CFG_REVIEW ] && [ ! -z $CFG_PATCHSET ]; then
        cd $CFG_REPO
        CFG_LAST2=$(echo $CFG_REVIEW | tail -c 3)
        git fetch https://$USER:$PASSWD@$CFG_SERVER/$CFG_REPO refs/changes/$CFG_LAST2/$CFG_REVIEW/$CFG_PATCHSET
        git checkout FETCH_HEAD
        cd ..
    fi

    REMOTE_CHASSIS_CONFIG=$CFG_REPO/$CFG_FOLDER/$NODE_NAME-chassis-config.pb.txt
    LOCAL_CHASSIS_CONFIG=chassis_config.pb.txt
    if [ -f $REMOTE_CHASSIS_CONFIG ]; then
        if [ -f $LOCAL_CHASSIS_CONFIG ] && [ ! -f $LOCAL_CHASSIS_CONFIG.old ]; then
            mv $LOCAL_CHASSIS_CONFIG $LOCAL_CHASSIS_CONFIG.old
        fi
        cp $REMOTE_CHASSIS_CONFIG $LOCAL_CHASSIS_CONFIG
    fi
