#!/usr/bin/env bash
set -euo pipefail

changed=0
k3s_changed=0
k3s_agent_changed=0

k3s_dropin="/host/etc/systemd/system/k3s.service.d/98-image-gc.conf"
k3s_agent_dropin="/host/etc/systemd/system/k3s-agent.service.d/98-image-gc.conf"

if [ -f "/host/etc/systemd/system/k3s.service" ] && [ ! -f "${k3s_dropin}" ]; then
  mkdir -p "$(dirname "${k3s_dropin}")"
  printf "[Service]\nEnvironment=\"K3S_KUBELET_ARG=image-gc-high-threshold=70\"\nEnvironment=\"K3S_KUBELET_ARG=image-gc-low-threshold=60\"\nEnvironment=\"K3S_KUBELET_ARG=image-gc-minimum-available=5Gi\"\n" > "${k3s_dropin}"
  changed=1
  k3s_changed=1
fi

if [ -f "/host/etc/systemd/system/k3s-agent.service" ] && [ ! -f "${k3s_agent_dropin}" ]; then
  mkdir -p "$(dirname "${k3s_agent_dropin}")"
  printf "[Service]\nEnvironment=\"K3S_KUBELET_ARG=image-gc-high-threshold=70\"\nEnvironment=\"K3S_KUBELET_ARG=image-gc-low-threshold=60\"\nEnvironment=\"K3S_KUBELET_ARG=image-gc-minimum-available=5Gi\"\n" > "${k3s_agent_dropin}"
  changed=1
  k3s_agent_changed=1
fi

if [ "${changed}" -eq 1 ]; then
  sleep "$(( (RANDOM % 300) + 10 ))"
  chroot /host /bin/systemctl daemon-reload
  if [ "${k3s_changed}" -eq 1 ]; then
    chroot /host /bin/systemctl restart k3s
  fi
  if [ "${k3s_agent_changed}" -eq 1 ]; then
    chroot /host /bin/systemctl restart k3s-agent
  fi
fi

sleep infinity
