#!/bin/bash
#
# lxc-stop script by Roberto Puzzanghera https://www.sagredo.eu
#
# This script stops a container running the lxc-stop command as the
# owner user if it is unpriviledged, or as root otherwise.
#
# Usage: lxd <container_name>
#

. my_lxc-common

NAME=$1
CONFIG=$LXC_PATH/$NAME/config

# Container name must be provided
if [ -z "$NAME" ]; then
  echo
  echo "Container name is required"
  echo "Usage: $0 <container_name>"
  echo
  exit 1
fi

# Exit if container does not exist
container_exists $NAME
if [ $? -eq 0 ]; then
  echo "Container $NAME does not exist. Exiting..."
  exit 1
fi

OWNER=$(owner $1)

# is it stopped already?
STATUS=$(is_it_running $NAME $OWNER)
if [ $STATUS -eq 0 ]; then
  echo "LXC container $NAME is already stopped. Exiting."
  exit 1
elif [ $STATUS -eq 2 ]; then
  echo "LXC container $NAME is frozen. Exiting."
  exit 1
fi

# stop
sudo -u $OWNER lxc-stop -n $NAME
sudo -u $OWNER lxc-wait -n $NAME -s STOPPED

exit 0
