#! /bin/bash
MYNAME=$(basename $0)
MYDIR=$(dirname $0)
MYDIR=$(readlink -m "$MYDIR")
VERSION="0.0.4"
VERBOSE=""
LOGFILE=""
SERVER=""

SSH="ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -o LogLevel=quiet"

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

#
# $*: 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 "$MYNAME($$) $*" >&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]...

  $MYNAME - Stops and destroys 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.
 --server=SERVER      Create the container on remote server.

 The container might be a container name or the IP address for a container.

EOF
    exit 0
}

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

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
            ;;

        --server)
            shift
            SERVER="$1"
            shift
            ;;

        --)
            shift
            break
            ;;

        *)
            ;;
    esac
done

#
# $1: the ip address to find
#
function find_name_for_ip()
{
    local ipToFind="$1"
    local lines
    local line
    local name
    local ip

    OIFS=$IFS; IFS=$'\n'; lines=($(sudo lxc-ls -f)); IFS=$OIFS
    
    for line in "${lines[@]}"; do 
        name=$(echo $line | awk '{print $1}')
        ip=$(echo $line | awk '{print $5}')

        if [ -z "$name" -o -z "$ip" ]; then
            continue
        fi

        if [ "$name" == "NAME" -a "$ip" == "IPV4" ]; then
            continue
        fi

        if [ "$ip" == "-" ]; then
            continue
        fi

        #printf "name: %-20s ip: %-20s\n" "$name" "$ip" >&2
        if [ "$ip" == "$ipToFind" ]; then
            echo "$name"
            break
        fi
    done
}


#
# $1: the name of the container to destroy.
#
function destroy_container()
{
    local container_name="$1"
    local real_name

    if [ -z "$container_name" ]; then
        printError "No container name, giving up."
        return 1
    fi

    if sudo test ! -d "/var/lib/lxc/$container_name"; then
        real_name=$(find_name_for_ip "$container_name")

        if sudo test -d "/var/lib/lxc/$real_name"; then
            destroy_container "$real_name"
            return $?
        fi

        printError "The container '$container_name' does not exist."
        return 1
    fi

    sudo lxc-stop -n "$container_name"
    sudo lxc-destroy -n "$container_name" >/dev/null 2>/dev/null

    if sudo test -d "/var/lib/lxc/$container_name"; then
        printVerbose "Removing root-fs."
        sudo umount /var/lib/lxc/$container_name
        sudo rmdir /var/lib/lxc/$container_name
    fi
}

#
# Checking command line arguments.
#
EXTRA_OPTIONS=$*

if [ -z "$1" ]; then
    printError "The arguments should be container name(s)."
    exit 6
fi

#
# Doing the job.
#
if [ -z "$SERVER" ]; then
    #
    # Destroy the container locally.
    #
    if [ "$VERSION_OPTION" ]; then
        printVersionAndExit
        exit 0
    else
        for container in $*; do
            destroy_container "$container"
        done
    fi
else
    #
    # We received the --server option and so we run the script on a remote
    # server.
    #
    printVerbose "Executing on server '$SERVER'."
    $SSH $SERVER -- \
        sudo $MYNAME \
            $VERSION_OPTION \
            $VERBOSE_OPTION \
            $EXTRA_OPTIONS

    $SSH $SERVER -- pip-host-control
fi

