#!/usr/bin/env bash
# Check every running container's image for a PHP binary (php, php-fpm, php8, ...)
# and print the PHP version if one is found.
#
# Detection uses `docker export` (works even on images without a shell, e.g.
# scratch/distroless). The version is read by running the binary directly with
# `docker exec <container> <binary> -v`, which also needs no shell.

set -euo pipefail

COL=80
PATTERN='(s?bin)/php(-fpm)?[0-9.]*$'

# newline-separated list of images already checked (macOS ships bash 3.2,
# which has no associative arrays, so `declare -A` is not an option)
seen_list=""

printf "%-${COL}s %s\n" "IMAGE" "PHP?"
printf "%-${COL}s %s\n" "-----" "----"

containers=$(docker ps --format '{{.ID}} {{.Image}}')

while read -r id image; do
  [[ -z "$id" ]] && continue

  # one check per unique image
  if grep -qxF -- "$image" <<< "$seen_list"; then continue; fi
  seen_list="$seen_list"$'\n'"$image"

  matches=$(docker export "$id" 2>/dev/null | tar -t 2>/dev/null | grep -E "$PATTERN" || true)

  if [[ -z "$matches" ]]; then
    printf "%-${COL}s %s\n" "$image" "no"
    continue
  fi

  # prefer the CLI binary (php, php8, ...) over php-fpm for the version lookup
  bin=$(echo "$matches" | grep -vE 'php-fpm' | head -n1 || true)
  [[ -z "$bin" ]] && bin=$(echo "$matches" | head -n1)
  bin="${bin#./}"

  version=$(docker exec "$id" "/$bin" -v 2>/dev/null | grep -oE 'PHP [0-9]+\.[0-9]+\.[0-9]+[^ ]*' | head -n1 || true)
  [[ -z "$version" ]] && version="version unknown"

  printf "%-${COL}s %s\n" "$image" "YES  $version  (/$bin)"
done <<< "$containers"
