#!/bin/bash
#
# lxc-freeze wrapper by Roberto Puzzanghera - https://www.sagredo.eu
#
# Usage: my_lxc-freeze -n <name>
#

. my_lxc-common

# expected usage
usage() {
  echo "Usage: $0 -n <name>
  $0 script takes the following options:
  -n  <name>    Name of the source container"
  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;;
    :) echo
       echo "Please provide all required options."
       echo
       usage;;
  esac
done

########################################################################################

# sanity check
if [ -z "$NAME" ]; then
  echo
  echo "Container <name> is required"
  echo
  usage
  exit 1
fi

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

# find the owner of the container
OWNER=$(owner $NAME)
if [ $? -ne 0 ]; then
  echo "Failed in retrieving the owner of the container $NAME. Exiting..."
  exit 1
fi

# is it running?
RUNNING=$(is_it_running $NAME $OWNER)
if [ $RUNNING -eq 0 ]; then
  echo "LXC container $NAME is not running. Exiting."
  exit 0
fi

CONFIG=$LXC_PATH/$NAME/config
if grep -q 'lxc.idmap' $CONFIG; then
  sudo -u $OWNER lxc-freeze -n $NAME --rcfile=$CONFIG
else
  lxc-freeze -n $NAME
fi

exit 0
