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

listen_ip="${REGISTRY_CACHE_LISTEN_IP:-10.27.27.239}"
storage_root="${REGISTRY_CACHE_STORAGE_ROOT:-/var/lib/docker-registry-cache}"

if [ "$(id -u)" -ne 0 ]; then
  echo "Run as root on the Proxmox host." >&2
  exit 1
fi

apt-get update
apt-get install -y docker-registry

systemctl disable --now docker-registry.service || true

mkdir -p /etc/docker/registry "${storage_root}"
chown docker-registry:docker-registry "${storage_root}"

cat >/etc/systemd/system/docker-registry-cache@.service <<'UNIT'
[Unit]
Description=Docker registry pull-through cache for %i
After=network.target

[Service]
User=docker-registry
Group=docker-registry
ExecStart=/usr/bin/docker-registry serve /etc/docker/registry/cache-%i.yml
Restart=on-failure
RestartSec=5s

[Install]
WantedBy=multi-user.target
UNIT

write_config() {
  local name="$1"
  local port="$2"
  local remote="$3"
  local dir="${storage_root}/${name}"

  mkdir -p "${dir}"
  chown docker-registry:docker-registry "${dir}"
  cat >"/etc/docker/registry/cache-${name}.yml" <<EOF
version: 0.1
log:
  fields:
    service: registry-cache-${name}
storage:
  cache:
    blobdescriptor: inmemory
  filesystem:
    rootdirectory: ${dir}
http:
  addr: ${listen_ip}:${port}
  headers:
    X-Content-Type-Options: [nosniff]
proxy:
  remoteurl: ${remote}
health:
  storagedriver:
    enabled: true
    interval: 10s
    threshold: 3
EOF
}

write_config dockerhub 5000 https://registry-1.docker.io
write_config ghcr 5001 https://ghcr.io
write_config quay 5002 https://quay.io
write_config k8s 5003 https://registry.k8s.io
write_config external-secrets 5004 https://oci.external-secrets.io
write_config rancher 5005 https://registry.rancher.com

systemctl daemon-reload
for name in dockerhub ghcr quay k8s external-secrets rancher; do
  systemctl enable --now "docker-registry-cache@${name}.service"
done

systemctl --no-pager --full status \
  docker-registry-cache@dockerhub.service \
  docker-registry-cache@ghcr.service \
  docker-registry-cache@quay.service \
  docker-registry-cache@k8s.service \
  docker-registry-cache@external-secrets.service \
  docker-registry-cache@rancher.service
