# shellcheck shell=bash
# shellcheck source=common.sh
source "$(dirname "${BASH_SOURCE[0]}")/common.sh"

docker_cmd() {
  if docker info >/dev/null 2>&1; then
    DOCKER=(docker)
  elif sudo -n docker info >/dev/null 2>&1; then
    DOCKER=(sudo docker)
  else
    DOCKER=(sudo docker)
  fi
}

require_container() {
  local name="${1:-$LM_CONTAINER}"
  docker_cmd
  if ! "${DOCKER[@]}" ps --format '{{.Names}}' | grep -qx "$name"; then
    echo "Container '$name' không chạy. Thử: ./scripts/lm.sh docker up" >&2
    exit 1
  fi
}

print_container_limits() {
  local name="${1:-$LM_CONTAINER}"
  local nano mem cpus ram_mb
  nano="$("${DOCKER[@]}" inspect -f '{{.HostConfig.NanoCpus}}' "$name")"
  mem="$("${DOCKER[@]}" inspect -f '{{.HostConfig.Memory}}' "$name")"
  cpus="$(awk "BEGIN { if ($nano > 0) printf \"%.2f\", $nano / 1000000000; else print \"unlimited\" }")"
  ram_mb=$((mem / 1048576))
  echo "  CPUs quota = ${cpus} core(s), RAM max = ${ram_mb} MB"
}
