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

threshold=70

sleep "$(( (RANDOM % 300) + 10 ))"

while true; do
  usage=$(df -P /host | awk 'NR==2 {gsub(/%/,"",$5); print $5}')
  if [ -z "${usage}" ]; then
    sleep 1800
    continue
  fi

  if [ "${usage}" -ge "${threshold}" ]; then
    chroot /host /bin/sh -c '
      if command -v crictl >/dev/null 2>&1; then
        crictl --runtime-endpoint=unix:///run/k3s/containerd/containerd.sock rmi --prune || true
      elif [ -x /usr/local/bin/crictl ]; then
        /usr/local/bin/crictl --runtime-endpoint=unix:///run/k3s/containerd/containerd.sock rmi --prune || true
      fi
    '
  fi

  sleep 21600
done
