#!/usr/bin/env python3
"""LLXC Wrapper for LXC Container Managemenr"""

# Copyright (c) 2012 Jonathan Carter
# This file is released under the MIT/expat license.

# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

# The little perfectionist in me likes to keep this alphabetical.
import argparse
import glob
import gettext
import os
import sys
import time
import tarfile
import shutil
import subprocess
import warnings

if os.getuid():
    opts = os.environ.get('llxcsudo', 'allow,env').split(",")
    if not "deny" in opts:
        cmd = ["sudo"]
        if "env" in opts:
            cmd.append("-E")

        sys.exit(subprocess.call(cmd + sys.argv))

# For now we need to filter the warning that python3-lxc produces
with warnings.catch_warnings():
    warnings.filterwarnings("ignore", category=Warning)
    import lxc

from gettext import gettext as _

# Set up translations via gettext
gettext.textdomain("llxc")

# Set Paths
CONTAINER_PATH = "/var/lib/lxc/"
AUTOSTART_PATH = "/etc/lxc/auto/"
CGROUP_PATH = "/sys/fs/cgroup/"
ARCHIVE_PATH = CONTAINER_PATH + ".archive/"
LLXCHOME_PATH = "/var/lib/llxc/"

# Other settings

# 5000 = 5 GiB
MIN_REQ_DISK_SPACE = 5000
KERNEL_VERSION = os.popen("uname -r").read().rstrip()

# Set colours, unless llxcmono is set
try:
    if os.environ['llxcmono']:
        GRAY = RED = GREEN = YELLOW = BLUE = ""
        PURPLE = CYAN = NORMAL = ""
except KeyError:
    # Light Colour Scheme
    GRAY = "\033[1;30m"
    RED = "\033[1;31m"
    GREEN = "\033[1;32m"
    YELLOW = "\033[1;33m"
    BLUE = "\033[1;34m"
    PURPLE = "\033[1;35m"
    CYAN = "\033[1;36m"
    NORMAL = "\033[0m"


def listing():
    """Provides a list of LXC Containers"""
    print (_("%s   NAME \tTASKS \t   STATUS \tIP_ADDR_%s%s"
           % (CYAN, ARGS.interface.swapcase(), NORMAL)))
    for container in glob.glob(CONTAINER_PATH + '*/config'):
        containername = container.replace(CONTAINER_PATH, "").rstrip("/config")
        cont = lxc.Container(containername)
        try:
            ipaddress = cont.get_ips(protocol="ipv4",
                                     interface="eth0", timeout=0.5)
            ipaddress = ipaddress[0]
        except TypeError:
            ipaddress = "Unavailable"
        except IndexError:
            ipaddress = "Unavailable"
        try: