#!/usr/bin/env bash

#   Copyright The containerd Authors.

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

#
# Writes a complete /etc/containerd/config.toml for a runsc (gVisor) setup,
# replacing any existing config.  This avoids fragile in-place patching of the
# file written by script/setup/config-containerd.
#
# Required environment variable:
#   CGROUP_DRIVER  — must be either "cgroupfs" or "systemd"
#
set -eux -o pipefail

: "${CGROUP_DRIVER:?CGROUP_DRIVER must be set to cgroupfs or systemd}"

script_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" > /dev/null 2>&1; pwd -P)"

SUDO=''
if [[ "$(id -u)" != "0" ]]; then
    SUDO='sudo'
fi

${SUDO} mkdir -p /etc/containerd

# Delegate to the shared helper so the config is defined in one place.
tmpfile="$(mktemp /tmp/containerd-config-runsc-XXXXXX.toml)"
trap 'rm -f "${tmpfile}"' EXIT
"${script_dir}/write-containerd-runsc-config.sh" "${tmpfile}" "${CGROUP_DRIVER}"
${SUDO} cp "${tmpfile}" /etc/containerd/config.toml

# Write the runsc shim config file.  write-runsc-shim-config.sh removes the
# higher-precedence /run/containerd/runsc/config.toml before writing to /etc,
# so stale files from previous runs cannot override the requested settings.
"${script_dir}/write-runsc-shim-config.sh" "${CGROUP_DRIVER}"
