#!/bin/bash
set -e
set -o pipefail

echo "progetto"  $1
REPO_NAME=$1
COMMIT_SHA=$(git rev-parse HEAD)
REGISTRY_URL=$2

# Esegui build_src.sh se presente prima della build container
if [ -f "./build_src.sh" ]; then
  echo "build_src.sh trovato, lo rendo eseguibile e lo eseguo"
  chmod +x ./build_src.sh
  ./build_src.sh
fi

# Controlla se la directory containers esiste
if [ ! -d "containers" ]; then
  echo "⚠️  Directory 'containers' non trovata, niente da fare"
  exit 0
fi

for dir in containers/*/; do
  CONTAINER_NAME=$(basename "$dir")
  if [ -d "src/${CONTAINER_NAME}" ]; then
    cp -R "src/${CONTAINER_NAME}/." "containers/${CONTAINER_NAME}/."
  else
    echo "Directory src/${CONTAINER_NAME} non trovata, skip copia sorgenti"
  fi
  ls -la $dir

  # Cerca sia dockerfile che Dockerfile
  if [ -f "$dir/dockerfile" ]; then
    DOCKERFILE="$dir/dockerfile"
  elif [ -f "$dir/Dockerfile" ]; then
    DOCKERFILE="$dir/Dockerfile"
  else
    echo "Dockerfile non trovato in $dir"
    continue
  fi



  IMAGE_TAG="${REGISTRY_URL}/${REPO_NAME}/${CONTAINER_NAME}:${COMMIT_SHA}"
  IMAGE_TAG_LATEST="${REGISTRY_URL}/${REPO_NAME}/${CONTAINER_NAME}:latest"
  echo "IMAGE_TAG_${CONTAINER_NAME}=$IMAGE_TAG" >> ./imglist

  PLATFORM_CONF="$dir/platform.conf"
  BUILD_PLATFORM=""
  if [ -f "$PLATFORM_CONF" ]; then
    BUILD_PLATFORM=$(grep -E '^[[:space:]]*platform[[:space:]]*=' "$PLATFORM_CONF" | tail -n 1 | cut -d '=' -f 2- | tr -d '[:space:]')
    if [ -n "$BUILD_PLATFORM" ]; then
      echo "platform.conf trovato in $dir: uso platform=$BUILD_PLATFORM"
    else
      echo "platform.conf trovato in $dir ma variabile platform non valorizzata, uso build standard"
    fi
  fi

  if [ -f "$DOCKERFILE" ]; then
    if [ -n "$BUILD_PLATFORM" ]; then
      docker buildx build --platform "$BUILD_PLATFORM" -t "$IMAGE_TAG" -t "$IMAGE_TAG_LATEST" -f "$DOCKERFILE" "$dir" --push
    else
      docker buildx build \
        --cache-from=type=registry,ref="${REGISTRY_URL}/${REPO_NAME}/${CONTAINER_NAME}:cache" \
        --cache-to=type=registry,ref="${REGISTRY_URL}/${REPO_NAME}/${CONTAINER_NAME}:cache",mode=max \
        -t "$IMAGE_TAG" -t "$IMAGE_TAG_LATEST" \
        -f "$DOCKERFILE" "$dir" --push
    fi
    echo "Build e push completate: $IMAGE_TAG"

    # Cleanup immagini locali dopo il push (buildx --push potrebbe non averle in locale)
    docker image rm -f "$IMAGE_TAG" "$IMAGE_TAG_LATEST" >/dev/null 2>&1 || true
    echo "Cleanup immagini locali completato: $IMAGE_TAG, $IMAGE_TAG_LATEST"

    # Cleanup globale ad ogni ciclo: immagini inutilizzate e cache builder
    docker image prune -af
    docker builder prune -af
  else
    echo "Dockerfile non trovato in $dir"
  fi
done
