#!/usr/bin/env bash
# Managed by Ansible — do not edit manually
# Weekly registry maintenance: remove stale uploads, run GC, prune dangling host images.
set -euo pipefail

LOG_TAG="registry-gc"
REGISTRY_COMPOSE_DIR="{{ registry_data_dir }}"
REGISTRY_DATA_DIR="{{ registry_data_dir }}/data"

log() { logger -t "$LOG_TAG" -- "$*"; echo "$(date -Iseconds) $*"; }

log "=== Registry cleanup started ==="

# 1. Remove stale upload sessions (failed or abandoned pushes)
find "{{ registry_data_dir }}/docker/registry/v2/repositories" \
  -type d -name '_uploads' -exec rm -rf {} + 2>/dev/null || true
log "Stale _uploads removed"

# 2. Garbage-collect unreferenced blobs (stop → collect → start)
cd "$REGISTRY_COMPOSE_DIR"
docker compose stop registry
docker run --rm \
  -v "${REGISTRY_DATA_DIR}:/var/lib/registry" \
  registry:2 garbage-collect /etc/docker/registry/config.yml
docker compose start registry
log "Registry GC complete, registry restarted"

# 3. Remove dangling Docker images from the host
PRUNED=$(docker image prune -f)
RECLAIMED=$(echo "$PRUNED" | awk '/Total reclaimed/{print $NF}')
log "Docker image prune complete: ${RECLAIMED:-0B} reclaimed"

log "=== Registry cleanup done ==="
