#!/bin/sh
# Keep the newest $1 image IDs of each repository, by creation time, and remove every other image
# no container uses, dangling ones included. An image ID counts once however many tags it has, and
# one kept by any of its repositories stays. A failed listing exits non-zero and removes nothing.
keep="$1"
case "$keep" in
  '' | *[!0-9]* | 0*) echo "invalid count '$keep'"; exit 2 ;;
esac

images=$(/usr/bin/docker image ls --no-trunc --format '{{.ID}} {{.Repository}} {{.CreatedAt}}') ||
  { echo "docker image ls failed"; exit 1; }
containers=$(/usr/bin/docker ps --all --quiet --no-trunc) || { echo "docker ps failed"; exit 1; }
used=""
if [ -n "$containers" ]; then
  # shellcheck disable=SC2086 # one argument per container ID
  used=$(/usr/bin/docker container inspect --format '{{.Image}}' $containers) ||
    { echo "cannot read the images of the containers"; exit 1; }
fi

# CreatedAt is local time with an offset ("2026-01-05 10:00:00 +0100 CET"): compare it as epoch
# seconds, or a change of offset would misorder the images.
table=$(printf '%s\n' "$images" | while read -r id repo day time offset _; do
  [ -n "$id" ] || continue
  created=$(date -d "$day $time $offset" +%s) || exit 1
  echo "$created $id $repo"
done) || { echo "cannot parse the creation time of an image"; exit 1; }

# Lines in: "used <id>", then "image <created> <id> <repo>", newest first within a repository.
# Lines out: "<number of references> <id>" for each image to remove.
remove=$({
  printf '%s\n' "$used" | sed -n 's/^./used &/p'
  printf '%s\n' "$table" | LC_ALL=C sort -k3,3 -k1,1nr -k2,2 | sed -n 's/^./image &/p'
} | awk -v keep="$keep" '
  $1 == "used" { used[$2] = 1; next }
  {
    id = $3; repo = $4; refs[id]++
    if (!(id in seen)) { seen[id] = 1; order[++n] = id }
    if (repo != "<none>" && !((repo, id) in counted)) {
      counted[repo, id] = 1
      if (++slots[repo] <= keep) kept[id] = 1
    }
  }
  END { for (i = 1; i <= n; i++) if (!(order[i] in kept) && !(order[i] in used)) print refs[order[i]], order[i] }
')

# An image with several references is refused by a plain rmi of its ID, so it needs --force.
printf '%s\n' "$remove" | {
  rc=0
  while read -r refs id; do
    [ -n "$id" ] || continue
    force=""
    [ "$refs" -gt 1 ] && force="--force"
    echo "removing image $id"
    # shellcheck disable=SC2086 # $force is empty or one word
    /usr/bin/docker rmi $force "$id" || rc=1
  done
  exit "$rc"
}
