#!/bin/sh -e

echo "List of all volumes:"
echo

# loop over all the data volumes
for podman_volume_id in $(podman volume ls --quiet); do
  echo "(Un)named volume: ${podman_volume_id}"

  # obtain size of the data volume by starting a podman container
  # that uses this data volume and determines the size of this data volume
  podman_volume_size=$(podman run --rm --tty \
    --volume "${podman_volume_id}":/volume_data alpine \
    sh -c "du -hs /volume_data | cut -f1")

  echo "    Size: ${podman_volume_size}"

  # determine number of stopped and running containers that
  # have a connection to this data volume
  num_related_containers=$(podman ps --all \
    --filter=volume="${podman_volume_id}" --quiet | wc -l)

  # if the number is non-zero, show info about container and image
  if [ "${num_related_containers}" -gt 0 ]; then
    echo "    Connected containers:"
    podman ps --all \
      --filter=volume="${podman_volume_id}" \
      --format "{{.Names}} [{{.Image}}] ({{.Status}})" \
      | while read -r containerDetails; do
        echo "    ${containerDetails}"
      done
  else
    echo "    No connected containers"
  fi
  echo
done
