#!/bin/bash

set -o errexit
set -o nounset
set -o pipefail

dropin_yaml() {
    local service=$1
    local name=$2
    local source=$3
    echo "# Autogenerated by hack/update-templates.sh; do not edit"
    echo "name: $service"
    echo "dropins:"
    echo "  - name: $name"
    echo "    contents: |"
    sed 's/^/      /' $source

}

write_dropin_yaml() {
    local service=$1
    local name=$2
    local source=$3
    local dst=$4
    echo "Generating template for drop-in $service::$name => $dst" >&2
    dropin_yaml "$service" "$name" "$source" > "$dst"
}

service_yaml() {
    local name=$1
    local enabled=$2
    local source=$3
    echo "# Autogenerated by hack/update-templates.sh; do not edit"
    echo "name: $name"
    echo "enabled: $enabled"
    echo "contents: |"
    sed 's/^/  /' $source
}

write_service_yaml() {
    local name=$1
    local enabled=$2
    local source=$3
    local dst=$4
    echo "Generating template for service $name (enabled=$enabled) => $dst" >&2
    service_yaml "$name" "$enabled" "$source" > "$dst"
}

SCRIPT_ROOT=$(dirname ${BASH_SOURCE})/..
UNITS=${SCRIPT_ROOT}/templates/common/_base/units

KUBENS_VENDOR=${SCRIPT_ROOT}/vendor/github.com/containers/kubensmnt/utils/systemd
echo "Updating templates from vendor/github.com/containers/kubensmnt/utils/systemd..." >&2
write_service_yaml kubens.service "false" ${KUBENS_VENDOR}/kubens.service ${UNITS}/kubens.service.yaml
write_dropin_yaml kubelet.service 01-kubens.conf ${KUBENS_VENDOR}/kubens-dropin.conf ${UNITS}/kubelet.service-kubens.yaml
write_dropin_yaml crio.service 01-kubens.conf ${KUBENS_VENDOR}/kubens-dropin.conf ${UNITS}/crio.service-kubens.yaml

log_cp() {
    echo "Copying $1 => $2"
    cp $1 $2
}

echo "Copying worker templates from equivalent master templates"
log_cp templates/master/01-master-kubelet/_base/files/kubenswrapper.yaml templates/worker/01-worker-kubelet/_base/files/kubenswrapper.yaml
