#!/usr/bin/env bash
# OpenFUT container registry helper.
#
# Usage:
#   ./scripts/registry.sh login            # docker login to the Gitea registry
#   ./scripts/registry.sh build            # build core + bridge images
#   ./scripts/registry.sh push             # push both images
#   ./scripts/registry.sh release          # build + push
#   ./scripts/registry.sh pull             # pull both images
#
# Config comes from .env (falls back to defaults matching docker-compose.yml).
# For login, set GITEA_USER and GITEA_TOKEN in the environment (a Gitea
# personal access token with package:write scope), or you'll be prompted.
set -euo pipefail

cd "$(dirname "$0")/.."

# Load .env if present (without clobbering already-exported vars).
if [[ -f .env ]]; then
  set -a; # shellcheck disable=SC1091
  source .env; set +a
fi

REGISTRY="${REGISTRY:-git.aleshym.co}"
NAMESPACE="${NAMESPACE:-openfut}"
TAG="${TAG:-latest}"

CORE_IMAGE="${REGISTRY}/${NAMESPACE}/openfut-core:${TAG}"
BRIDGE_IMAGE="${REGISTRY}/${NAMESPACE}/openfut-bridge:${TAG}"

log() { printf '\033[1;36m==>\033[0m %s\n' "$*"; }

cmd_login() {
  if [[ -n "${GITEA_USER:-}" && -n "${GITEA_TOKEN:-}" ]]; then
    log "Logging in to ${REGISTRY} as ${GITEA_USER} (token)"
    printf '%s' "${GITEA_TOKEN}" | docker login "${REGISTRY}" -u "${GITEA_USER}" --password-stdin
  else
    log "Logging in to ${REGISTRY} (interactive; set GITEA_USER/GITEA_TOKEN to automate)"
    docker login "${REGISTRY}"
  fi
}

cmd_build() {
  log "Building ${CORE_IMAGE}"
  docker build -t "${CORE_IMAGE}" ./openfut-core
  log "Building ${BRIDGE_IMAGE}"
  docker build -t "${BRIDGE_IMAGE}" ./openfut-bridge
}

cmd_push() {
  log "Pushing ${CORE_IMAGE}"
  docker push "${CORE_IMAGE}"
  log "Pushing ${BRIDGE_IMAGE}"
  docker push "${BRIDGE_IMAGE}"
}

cmd_pull() {
  docker pull "${CORE_IMAGE}"
  docker pull "${BRIDGE_IMAGE}"
}

case "${1:-}" in
  login)   cmd_login ;;
  build)   cmd_build ;;
  push)    cmd_push ;;
  pull)    cmd_pull ;;
  release) cmd_build; cmd_push ;;
  *) echo "Usage: $0 {login|build|push|pull|release}" >&2; exit 2 ;;
esac
