# Copyright 2018 TriggerMesh, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: registry-etc-hosts-update
  namespace: kube-system
spec:
  selector:
    matchLabels:
      app: registry-etc-hosts-update
  template:
    metadata:
      labels:
        app: registry-etc-hosts-update
    spec:
      initContainers:
      - name: update
        image: debian:stretch-slim
        volumeMounts:
        - name: etchosts
          mountPath: /host-etc/hosts
          readOnly: false
        env:
        - name: REGISTRY_SERVICE_HOSTS
          value: >-
            knative.registry.svc.cluster.local
            builds.registry.svc.cluster.local
            kanikocache.registry.svc.cluster.local
        command:
        - bash
        - -ce
        - |
          NL=$'\n'
          HOSTS="$(cat /host-etc/hosts)"
          for H in $REGISTRY_SERVICE_HOSTS; do
            ent=$(getent hosts $H);
            [ -z "$ent" ] && echo "Failed to get hosts entry for $H" && exit 1;
            echo "$HOSTS" | grep " $H"  || HOSTS="$HOSTS$NL$ent";
            echo "$HOSTS" | grep "$ent" || HOSTS=$(echo "$HOSTS" | sed "s|.* $H|$ent|");
          done;
          echo "$HOSTS" | diff -u /host-etc/hosts - || echo "$HOSTS" > /host-etc/hosts
          echo "Done."
      containers:
      - name: init-container-did-the-work
        image: gcr.io/google_containers/pause-amd64:3.1@sha256:59eec8837a4d942cc19a52b8c09ea75121acc38114a2c68b98983ce9356b8610
      terminationGracePeriodSeconds: 30
      volumes:
      - name: etchosts
        hostPath:
          path: /etc/hosts
