#!/bin/sh -e

dry_run=""

while [ "$#" -gt 0 ]; do
    case "$1" in
    --debug|--debug=true)
        set -x
        ;;
    --dry-run|--dry-run=true)
        dry_run="log red"
        ;;
    *)
        ;;
    esac
    shift
done

log() {
    case $1 in
        blue)
            color='\033[0;34m'
            ;;
        green)
            color='\033[0;32m'
            ;;
        red)
            color='\033[0;31m'
            ;;
        *)
            color='\033[0m'
            ;;
    esac
    shift

    echo -e "[$(date +"%Y-%m-%d %H:%M:%S")] $color$@\033[0m";
}

log blue "Orphaned folders cleanup start."

log blue "execute garbage-collect deletes layers not referenced by any manifests"

registry garbage-collect /etc/docker/registry/config.yml

registry_url="http://localhost:5000/v2"

# {"repositories":["hello-world","k8s/conformance"]}
images=$(wget -qO- "${registry_url}/_catalog" | sed -n 's/.*"repositories":\s*\[\([^]]*\)\].*/\1/p' | sed 's/"//g; s/,/\n/g')

log blue "repositories:\n$images"

for image in ${images}; do
    # {"name":"hello-world","tags":null}
    # {"name":"hello-world","tags":["1.0.0","latest"]}
    tag_list=$(wget -qO- "${registry_url}/${image}/tags/list")
    if echo "$tag_list" | grep -q '"tags":null'; then
        log red $tag_list
        log red "delete empty repository $image"
        $dry_run rm -rf "/var/lib/registry/docker/registry/v2/repositories/${image}"
    else
        log green $tag_list
    fi
done

log blue "Orphaned folders cleanup completed."
