#!/bin/bash
#
# lxc-execute wrapper script by Roberto Puzzanghera
#
# Usage: lxe <container_name> -- command
#

. my_lxc-common

# display the expected usage
usage() {
  echo "Usage: $0 -n <name> -- command

  $0 script takes the following options:
  -n Name of the container
  -h Print help options and exit"
  exit 1
}

# Define the flags the user can pass to the script
while getopts :n:h option
  do
    case "${option}" in
    n) NAME=${OPTARG};;
    h) usage;;
    *) usage;;
  esac
done

# sanity check
if [ $# -lt 4 ]; then
  usage
  exit 1
fi

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

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

# stop
stop_container $NAME
if [ $? -ne 0 ]; then
  echo "Failed in stopping container $NAME. Exiting..."
  exit 1
fi

CONFIG=$LXC_PATH/$NAME/config

# find the owner of the container (NB: no spaces around the '=')
OWNER=$(owner $NAME)

sudo -u $OWNER lxc-execute -n $NAME -f $CONFIG -- $4

exit 0

