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

      [Service]
      Type=oneshot
      EnvironmentFile=/etc/sysconfig/heat-params
      ExecStart=/etc/sysconfig/enable-network-service.sh

      [Install]
      WantedBy=multi-user.target

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

      if [ "$NETWORK_DRIVER" != "flannel" ]; then
          exit 0
      fi

      if [ -z "${KUBE_NODE_IP}" ]; then
        KUBE_NODE_IP=$(curl -s http://169.254.169.254/latest/meta-data/local-ipv4)
      fi

      ENV_FILE=/etc/flannel/options.env
      mkdir -p $(dirname $ENV_FILE)
      cat > $ENV_FILE <<EOF
      FLANNELD_IFACE=${KUBE_NODE_IP}
      FLANNELD_ETCD_ENDPOINTS=http://127.0.0.1:2379
      EOF

      DROP_IN_FILE=/etc/systemd/system/flanneld.service.d/40-ExecStartPre-symlink.conf
      mkdir -p $(dirname $DROP_IN_FILE)
      cat > $DROP_IN_FILE <<EOF
      [Service]
      Environment=ETCD_SSL_DIR=${KUBE_CERTS_PATH}
      ExecStartPre=/usr/bin/ln -sf /etc/flannel/options.env /run/flannel/options.env
      EOF

      DROP_IN_FILE=/etc/systemd/system/flanneld.service.d/50-Environment.conf
      mkdir -p $(dirname $DROP_IN_FILE)
      cat > $DROP_IN_FILE <<EOF
      [Service]
      EnvironmentFile=/etc/environment
      EOF

      DOCKER_FLANNEL_CONF=/etc/systemd/system/docker.service.d/40-flannel.conf
      mkdir -p $(dirname $DOCKER_FLANNEL_CONF)
      cat > $DOCKER_FLANNEL_CONF <<EOF
      [Unit]
      Requires=flanneld.service
      After=flanneld.service
      [Service]
      EnvironmentFile=/etc/kubernetes/cni/docker_opts_cni.env
      EOF

      CNI=/etc/kubernetes/cni/net.d/10-flannel.conf
      mkdir -p $(dirname $CNI)
      cat << EOF > $CNI
      {
          "name": "podnet",
          "type": "flannel",
          "delegate": {
              "isDefaultGateway": true
          }
      }
      EOF

      DOCKER_FLANNEL_CONF=/etc/kubernetes/cni/docker_opts_cni.env
      mkdir -p $(dirname $DOCKER_FLANNEL_CONF)
      cat > $DOCKER_FLANNEL_CONF <<EOF
      DOCKER_OPT_BIP=""
      DOCKER_OPT_IPMASQ=""
      EOF

      systemctl enable flanneld
      systemctl --no-block start flanneld
