#! /bin/bash
MYNAME=$(basename $0)
MYDIR=$(dirname $0)
MYDIR=$(readlink -m "$MYDIR")
VERSION="0.0.5"
VERBOSE=""
LOGFILE=""
CONTAINER=""
SOURCE_SERVER=""
TARGET_SERVER=""
SSH="ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -o LogLevel=quiet"
OPTION_GZIP=""
OPTION_START=""
START_OPTION=""

#
# Prints the software version and exits.
#
function printVersionAndExit()
{
    echo "$MYNAME Version $VERSION on $(hostname)" >&2
    exit 0
}

#
# $*: the error message
#
# Prints an error message to the standard error. The text will not mixed up with
# the data that is printed to the standard output.
#
function printError()
{
    local datestring=$(date "+%Y-%m-%d %H:%M:%S")

    echo -e "$*" >&2

    if [ "$LOGFILE" ]; then
        echo -e "$datestring ERROR $MYNAME($$) $*" >>"$LOGFILE"
    fi
}

#
# $*: the message
#
# Prints all the arguments but only if the program is in the verbose mode.
#
function printVerbose()
{
    local datestring=$(date "+%Y-%m-%d %H:%M:%S")

    if [ "$VERBOSE" == "true" ]; then
        echo -e "$MYNAME($$) $*" >&2
    fi

    if [ "$LOGFILE" ]; then
        echo -e "$datestring DEBUG $MYNAME($$) $*" >>"$LOGFILE"
    fi
}

function printHelpAndExit()
{
cat <<EOF
Usage:
  $MYNAME [OPTION]... [CONTAINER_NAME]...

  $MYNAME - Creates archives of containers.

 -h, --help             Print this help and exit.
 -v, --version          Print version information and exit.
 --verbose              Print more messages.
 --log-file=FILE        Store all the messages in the given file too.
 --source-server=SERVER The server to copy from.
 --target-server=SERVER The server to copy to.
 --gzip                 Compress the archive file.
 --start                Start the container after moving it.

EXAMPLE
  pip-container-move --source-server=core1 --target-server=host01 mqtt 

EOF
    exit 0
}

ARGS=$(\
    getopt \
        -o hvs:c:l \
        -l "help,verbose,version,log-file:,source-server:,target-server:,\
gzip,start" \
        -- "$@")

if [ $? -ne 0 ]; then
    exit 6
fi

eval set -- "$ARGS"
while true; do
    case "$1" in
        -h|--help)
            shift
            printHelpAndExit
            ;;

        --verbose)
            shift
            VERBOSE="true"
            VERBOSE_OPTION="--verbose"
            ;;

        -v|--version)
            shift
            VERSION_OPTION="--version"
            ;;

        --log-file)
            shift
            LOGFILE=$(readlink -m "$1")
            shift
            ;;

        --source-server)
            shift
            SOURCE_SERVER="$1"
            SOURCE_SERVER_OPTION="--source-server=$SOURCE_SERVER"
            shift
            ;;
        
        --target-server)
            shift
            TARGET_SERVER="$1"
            TARGET_SERVER_OPTION="--target-server=$TARGET_SERVER"
            shift
            ;;

        --gzip)
            shift
            OPTION_GZIP="true"
            ;;

        --start)
            shift
            OPTION_START="true"
            START_OPTION="--start"
            ;;

        --)
            shift
            break
            ;;

        *)
            ;;
    esac
done

CONTAINER="$1"
EXTRA_OPTIONS="$*"

if [ "$VERSION_OPTION" ]; then
    printVersionAndExit
fi

#
# Checking the command line options.
#
if [ -z "$CONTAINER" ]; then
    printError "The first argument should be the name of the container."
    exit 6
fi

#
# Doing the job.
#
if [ "$SOURCE_SERVER" ]; then
    $SSH $SOURCE_SERVER -- \
        $MYNAME \
        $VERSION_OPTION \
        $VERBOSE_OPTION \
        $START_OPTION \
        $TARGET_SERVER_OPTION \
        $EXTRA_OPTIONS 
else
    if [ "$OPTION_GZIP" ]; then
        tar_file_name="/var/tmp/pip_container_move_$$.tar.gz"
    else
        tar_file_name="/var/tmp/pip_container_move_$$.tar"
    fi

    source_dir="/var/lib/lxc/$CONTAINER"

    #if [ ! -d "$CONTAINER" ]; then
    #    printError "Can not find container '$CONTAINER'."
    #    exit 1
    #fi
    echo "Stopping the container..."
    sudo lxc-stop -n "$CONTAINER" >/dev/null 2>/dev/null

    echo "Creating archive..."
    if [ "$OPTION_GZIP" ]; then
        sudo tar --numeric-owner -czf "$tar_file_name" "$source_dir" 2>/dev/null
    else
        sudo tar --numeric-owner -cf "$tar_file_name" "$source_dir" 2>/dev/null
    fi

    #sudo lxc-start --name $CONTAINER
    

    echo "Moving archive file..."
    scp "$tar_file_name" $TARGET_SERVER:/var/tmp 2>/dev/null
    sudo rm -f "$tar_file_name"

    echo "Uncompressing archive..."
    if [ "$OPTION_GZIP" ]; then
        $SSH $TARGET_SERVER 2>/dev/null -- \
            sudo tar xzf "$tar_file_name" -C / 2>/dev/null
    else
        $SSH $TARGET_SERVER 2>/dev/null -- \
            sudo tar xf "$tar_file_name" -C / 2>/dev/null
    fi
   
    if [ "$OPTION_START" ]; then
        echo "Starting container '$CONTAINER'..."
        $SSH $TARGET_SERVER 2>/dev/null -- \
            sudo lxc-start --name $CONTAINER
    fi

    $SSH $TARGET_SERVER 2>/dev/null -- \
        sudo rm -f "$tar_file_name" 2>/dev/null
fi
