#!/bin/bash
#
# lxc-ls wrapper script by Roberto Puzzanghera https://www.sagredo.eu
#

. my_lxc-common

CONFIG=$LXC_PATH/$1/config

GREEN='\033[1;32m'
RED='\033[1;31m'
YEL='\033[1;33m'
HIGHLIGHT=$YEL
NC='\033[0m' # No Color

check_user() {
  egrep  -q -i "^${1}:" /etc/passwd
  if [ $? -eq 0 ]; then
    return 0
  else
    return 1
  fi
}

if [ "$1" == "--active" ] || [ "$1" == "--frozen" ] || [ "$1" == "--running" ]; then
  # print the active privileged containers first
  lxc-ls --active
  # then print the active unprivileged containers
  # Get the owners array
  users=($(list_owners))
  # lxc-ls --active for each owner
  for u in "${users[@]}"; do
    sudo -u $u lxc-ls --active
  done
elif [ -n "$1" ]; then
  # sanity check
  check_user $1
  if [ $? -eq 1 ]; then
    echo -e "${GREEN}User ${HIGHLIGHT}${1}${GREEN} does not exist. Exiting...${NC}"
    exit 1
  fi
  # unprivileged containers of user $1
  echo -e "${GREEN}Unprivileged running containers of user ${HIGHLIGHT}${1}${NC}"
  sudo -u $1 lxc-ls --fancy
else
  # show normal lxc-ls output
  echo -e "${GREEN}All containers${NC}"
  lxc-ls --fancy

  # Get the owners array
  users=($(list_owners))

  # Show containers belonging to each user
  for user in "${users[@]}"
  do
     echo -e "${GREEN}Unprivileged running containers of user ${HIGHLIGHT}${user}${NC}"
     sudo -u $user lxc-ls --fancy
  done
fi

exit 0
