#!/usr/bin/env bash
# Docker security auditor — checks running containers and daemon configuration.
# Usage: bash scripts/docker_audit.sh
set -euo pipefail

echo "=== Docker Security Audit ==="
echo ""

echo "--- Docker Daemon ---"
docker info --format '{{json .SecurityOptions}}' 2>/dev/null | jq -r '.[]' 2>/dev/null || echo "  Cannot read daemon info"

echo ""
echo "--- Privileged Containers ---"
docker ps --format '{{.Names}}' | while read -r name; do
  priv=$(docker inspect "$name" --format '{{.HostConfig.Privileged}}' 2>/dev/null)
  if [ "$priv" = "true" ]; then
    echo "  🔴 $name: PRIVILEGED"
  fi
done

echo ""
echo "--- Containers as Root ---"
docker ps --format '{{.Names}}' | while read -r name; do
  user=$(docker inspect "$name" --format '{{.Config.User}}' 2>/dev/null)
  if [ -z "$user" ] || [ "$user" = "0" ] || [ "$user" = "root" ]; then
    echo "  ⚠️  $name: running as root"
  fi
done

echo ""
echo "--- Containers with Host Network ---"
docker ps --format '{{.Names}}' | while read -r name; do
  net=$(docker inspect "$name" --format '{{.HostConfig.NetworkMode}}' 2>/dev/null)
  if [ "$net" = "host" ]; then
    echo "  ⚠️  $name: host network"
  fi
done

echo ""
echo "--- Images Without Tags ---"
docker images --format '{{.Repository}}:{{.Tag}}' | grep -E '<none>|:$' || echo "  ✅ All images tagged"

echo ""
echo "--- Outdated Base Images ---"
docker images --format '{{.Repository}}:{{.Tag}} ({{.CreatedSince}})' | head -10
