#cloud-config
write_files:
  - path: /etc/systemd/system/write-network-config.service
    owner: "root:root"
    permissions: "0644"
    content: |
      [Unit]
      Description=Write Network Config

      [Service]
      Type=oneshot
      ExecStart=/etc/sysconfig/write-network-config.sh

      [Install]
      WantedBy=multi-user.target

  - path: /etc/sysconfig/write-network-config.sh
    owner: "root:root"
    permissions: "0755"
    content: |
      #!/bin/sh

      . /etc/sysconfig/heat-params
      if [ "$NETWORK_DRIVER" != "flannel" ]; then
          exit 0
      fi

      FLANNEL_JSON=/etc/sysconfig/flannel-network.json
      cat > $FLANNEL_JSON <<EOF
      {
          "Network": "$FLANNEL_NETWORK_CIDR",
          "Subnetlen": $FLANNEL_NETWORK_SUBNETLEN,
          "Backend": {
              "Type": "$FLANNEL_BACKEND"
          }
      }
      EOF

      FLANNEL_ETCD="http://127.0.0.1:2379"
      FLANNEL_ETCD_KEY="/coreos.com/network"
      while ! curl -sf -L ${FLANNEL_ETCD}/v2/keys${FLANNEL_ETCD_KEY}/config \
        -X PUT --data-urlencode value@${FLANNEL_JSON}; do
          echo "waiting for etcd"
          sleep 1
      done
