#!/bin/bash
#
# Retag legacy Docker images to the new ghcr.io/open-prison-education namespace.
#
# Old OPE servers pulled images from Docker Hub under operepo/* and various
# upstream repos. This script retags every known image so the existing local
# cache can be reused with the new docker-compose configuration — no need to
# re-pull gigabytes over a slow or air-gapped link.
#
# Usage:
#   ./scripts/retag-images.sh          # retag only
#   ./scripts/retag-images.sh --push   # retag and push to ghcr.io
#

set -e

REGISTRY="ghcr.io/open-prison-education"
PUSH=false
if [[ "$1" == "--push" ]]; then
  PUSH=true
fi

retag() {
  local src="$1" dest="$2"
  if docker image inspect "$src" &>/dev/null; then
    echo "  $src -> $dest"
    docker tag "$src" "$dest"
    if $PUSH; then
      docker push "$dest"
    fi
  else
    echo "  SKIP $src (not found locally)"
  fi
}

RETAGGED=0
SKIPPED=0

count() {
  if docker image inspect "$1" &>/dev/null; then
    RETAGGED=$((RETAGGED + 1))
  else
    SKIPPED=$((SKIPPED + 1))
  fi
}

echo "=== Retagging operepo/* images ==="
for img in ope-canvas ope-smc ope-websites ope-gateway ope-canvas-rce \
           ope-canvas-mathman ope-redis ope-postgresql ope-dns ope-letsencrypt \
           ope-fog; do
  count "operepo/${img}:release"
  retag "operepo/${img}:release" "${REGISTRY}/${img}:release"
done

echo ""
echo "=== Done: ${RETAGGED} retagged, ${SKIPPED} skipped ==="
if $PUSH; then
  echo "All retagged images were pushed to ${REGISTRY}."
else
  echo "Run with --push to also push images to ${REGISTRY}."
fi
