# Copyright 2021 Kontain
# Derived from:
# Copyright 2019 Google LLC
#
# 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: v1
kind: ConfigMap
metadata:
  name: kontain-install-entrypoint
  namespace: kube-system
  labels:
    app: kontain-init
data:
  entrypoint.sh: |
    #!/usr/bin/env bash

    set -x
    set -euo pipefail

    ROOT_MOUNT_DIR="${ROOT_MOUNT_DIR:-/root}"

    source /scripts-lib/kontain_install_lib.sh

    echo "Install Kontain Runtime Artifacts (KM & KRUN)"
    install_kontain_artifacts

    echo "Add Kontain Runtime to containerd configuration"
    containerd_conf_file="/etc/containerd/config.toml"
    runtime="krun"
    configuration="configuration"
    pluginid=cri
    if grep -q "version = 2\>" $containerd_conf_file; then
       pluginid=\"io.containerd.grpc.v1.cri\"
    fi

    runtime_table="plugins.${pluginid}.containerd.runtimes.$runtime"
    runtime_type="io.containerd.$runtime.v2"
    options_table="$runtime_table.options"
    config_path=""
    if grep -q "\[$runtime_table\]" $containerd_conf_file; then
        echo "Configuration exists for $runtime_table, overwriting"
        sed -i "/\[$runtime_table\]/,+1s#runtime_type.*#runtime_type = \"${runtime_type}\"#" $containerd_conf_file
    else
        cat <<-EOT | tee -a /etc/containerd/config.toml
        	[$runtime_table]
        	runtime_type = "${runtime_type}"
        	privileged_without_host_devices = true
        	pod_annotations = ["app.kontain.*"]
    EOT
    fi

    [ -c /root/dev/kvm ] && chmod 666 /root/dev/kvm

    echo "restart containerd"
    systemctl daemon-reload
    systemctl restart containerd

    sleep infinity
