#cloud-config
write_files:
  - path: /etc/systemd/system/configure-etcd.service
    owner: "root:root"
    permissions: "0644"
    content: |
      [Unit]
      Description=Configure etcd

      [Service]
      Type=oneshot
      ExecStart=/etc/sysconfig/configure-etcd.sh

      [Install]
      WantedBy=multi-user.target

  - path: /etc/sysconfig/configure-etcd.sh
    owner: "root:root"
    permissions: "0755"
    content: |
      #!/bin/sh

      . /etc/sysconfig/heat-params
      myip=$(curl -s http://169.254.169.254/latest/meta-data/local-ipv4)

      DROP_IN_FILE=/etc/systemd/system/etcd2.service.d/20-configure-etcd.conf
      mkdir -p $(dirname $DROP_IN_FILE)
      cert_dir="/etc/kubernetes/ssl"
      protocol="https"

      if [ "$TLS_DISABLED" = "True" ]; then
          protocol="http"
      fi
      cat > $DROP_IN_FILE <<EOF
      [Service]
      Environment=ETCD_NAME=$myip
      Environment=ETCD_DATA_DIR=/var/lib/etcd/default.etcd
      Environment=ETCD_LISTEN_CLIENT_URLS=$protocol://$myip:2379,http://127.0.0.1:2379
      Environment=ETCD_LISTEN_PEER_URLS=$protocol://$myip:2380

      Environment=ETCD_ADVERTISE_CLIENT_URLS=$protocol://$myip:2379,http://127.0.0.1:2379
      Environment=ETCD_INITIAL_ADVERTISE_PEER_URLS=$protocol://$myip:2380
      Environment=ETCD_DISCOVERY=$ETCD_DISCOVERY_URL
      EOF

      if [ "$TLS_DISABLED" = "False" ]; then

      cat >> $DROP_IN_FILE <<EOF
      Environment=ETCD_CA_FILE=$cert_dir/ca.pem
      Environment=ETCD_CERT_FILE=$cert_dir/apiserver.pem
      Environment=ETCD_KEY_FILE=$cert_dir/apiserver-key.pem
      Environment=ETCD_PEER_CA_FILE=$cert_dir/ca.pem
      Environment=ETCD_PEER_CERT_FILE=$cert_dir/apiserver.pem
      Environment=ETCD_PEER_KEY_FILE=$cert_dir/apiserver-key.pem
      EOF

      fi

      if [ -n "$HTTP_PROXY" ]; then
          echo "Environment=ETCD_DISCOVERY_PROXY=$HTTP_PROXY" >> $DROP_IN_FILE
      fi

      systemctl enable etcd2
      systemctl --no-block start etcd2
