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

      [Service]
      Type=oneshot
      ExecStart=/etc/sysconfig/add-proxy.sh

      [Install]
      WantedBy=multi-user.target

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

      . /etc/sysconfig/heat-params

      DOCKER_HTTP_PROXY_CONF=/etc/systemd/system/docker.service.d/http_proxy.conf

      DOCKER_HTTPS_PROXY_CONF=/etc/systemd/system/docker.service.d/https_proxy.conf

      DOCKER_NO_PROXY_CONF=/etc/systemd/system/docker.service.d/no_proxy.conf

      DOCKER_RESTART=0

      ENVIRONMENT=/etc/environment

      mkdir -p /etc/systemd/system/docker.service.d

      if [ -n "$HTTP_PROXY" ]; then
          cat <<EOF | sed "s/^ *//" > $DOCKER_HTTP_PROXY_CONF
          [Service]
          Environment=HTTP_PROXY=$HTTP_PROXY
      EOF

        DOCKER_RESTART=1

        echo "http_proxy=$HTTP_PROXY" >> $ENVIRONMENT
      fi

      if [ -n "$HTTPS_PROXY" ]; then
          cat <<EOF | sed "s/^ *//" > $DOCKER_HTTPS_PROXY_CONF
          [Service]
          Environment=HTTPS_PROXY=$HTTPS_PROXY
      EOF

        DOCKER_RESTART=1

        echo "https_proxy=$HTTPS_PROXY" >> $ENVIRONMENT
      fi

      if [ -n "$NO_PROXY" ]; then
          cat <<EOF | sed "s/^ *//" > $DOCKER_NO_PROXY_CONF
          [Service]
          Environment=NO_PROXY=$NO_PROXY
      EOF

        DOCKER_RESTART=1

        echo "no_proxy=$NO_PROXY" >> ENVIRONMENT
      fi

      if [ "$DOCKER_RESTART" -eq 1 ]; then
        systemctl daemon-reload
        systemctl --no-block restart docker.service
      fi
