#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
      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

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

      myip=$(curl -s http://169.254.169.254/latest/meta-data/local-ipv4)
      ETCD_SERVER_IP=${ETCD_SERVER_IP:-127.0.0.1}

      CERT_DIR=/etc/kubernetes/ssl
      PROTOCOL=https

      if [ "$TLS_DISABLED" = "True" ]; then
        PROTOCOL=http
      fi

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

      if [ "$TLS_DISABLED" = "False" ]; then
        cat >> $ENV_FILE <<EOF
      FLANNELD_ETCD_CAFILE=$CERT_DIR/ca.pem
      FLANNELD_ETCD_CERTFILE=$CERT_DIR/apiserver.pem
      FLANNELD_ETCD_KEYFILE=$CERT_DIR/apiserver-key.pem
      EOF
      fi

      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=$CERT_DIR"
      ExecStartPre=/usr/bin/ln -sf /etc/flannel/options.env /run/flannel/options.env
      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
      EOF

      systemctl enable flanneld
      systemctl --no-block start flanneld
