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

limit_line="LimitNOFILE=1048576"
sysctl_file="/host/etc/sysctl.d/99-atlas-inotify.conf"
changed=0

for unit in k3s k3s-agent; do
  unit_file="/host/etc/systemd/system/${unit}.service"
  if [ -f "${unit_file}" ]; then
    dropin_dir="/host/etc/systemd/system/${unit}.service.d"
    dropin_file="${dropin_dir}/99-nofile.conf"
    if [ ! -f "${dropin_file}" ] || ! grep -q "${limit_line}" "${dropin_file}"; then
      mkdir -p "${dropin_dir}"
      printf "[Service]\n%s\n" "${limit_line}" > "${dropin_file}"
      changed=1
    fi
  fi
done

mkdir -p "$(dirname "${sysctl_file}")"
cat > "${sysctl_file}" <<'EOF'
fs.inotify.max_user_instances = 8192
fs.inotify.max_user_watches = 524288
fs.inotify.max_queued_events = 32768
EOF

printf "8192" > /host/proc/sys/fs/inotify/max_user_instances
printf "524288" > /host/proc/sys/fs/inotify/max_user_watches
printf "32768" > /host/proc/sys/fs/inotify/max_queued_events

if [ "${changed}" -eq 1 ]; then
  sleep "$(( (RANDOM % 300) + 10 ))"
  chroot /host /bin/systemctl daemon-reload
  for unit in k3s k3s-agent; do
    if [ -f "/host/etc/systemd/system/${unit}.service" ]; then
      chroot /host /bin/systemctl restart "${unit}"
    fi
  done
fi

sleep infinity
