#!/bin/bash
# Repository pre-command hook: the agent runs it on the host after checkout,
# before the docker plugin pulls the job image.

# Arm CPU test hosts pull a multi-GB per-commit image every run and nothing
# removes the old ones, so the pull eventually fails with "no space left on
# device". Once the Docker root filesystem crosses DISK_USAGE_THRESHOLD percent,
# drop images that no container uses and that were built more than
# IMAGE_MAX_AGE ago.
# Plugin settings reach only the plugin's own hooks; BUILDKITE_PLUGINS (the
# step's plugin JSON) is visible here.
if [[ "${BUILDKITE_PLUGINS:-}" == *-arm64-cpu\"* ]]; then
    DISK_USAGE_THRESHOLD=${DISK_USAGE_THRESHOLD:-80}
    IMAGE_MAX_AGE=${IMAGE_MAX_AGE:-2h}
    docker_root=$(docker info -f '{{.DockerRootDir}}' 2>/dev/null || true)
    if [[ -n "$docker_root" ]]; then
        disk_usage=$(df "$docker_root" 2>/dev/null | tail -1 | awk '{print $5}' | tr -d '%' || true)
        if [[ "${disk_usage:-0}" -gt "$DISK_USAGE_THRESHOLD" ]]; then
            echo "--- :broom: Disk usage ${disk_usage}% exceeds ${DISK_USAGE_THRESHOLD}%, pruning images"
            docker image prune --force --all --filter "until=${IMAGE_MAX_AGE}" || true
        fi
    fi
fi
