#!/usr/bin/python
import argparse, os, sys, pwd, gettext

from gettext import gettext as _
gettext.textdomain("arkose")

currentdir=os.path.split(os.path.realpath(__file__))[0]
if os.path.exists(os.path.join(currentdir, "../arkose/__init__.py")):
    sys.path.insert(0, os.path.join(currentdir, ".."))

import arkose

if not os.geteuid() == 0:
    print(_("You must be root to use this command"))
    sys.exit(1)

# Get all the parameters
parser = argparse.ArgumentParser(description=_("Arkose application container"), add_help=False,
        epilog=_("""For X to work on >= 2.6.36, you need one of -n (network) or -T (real /tmp).
For older versions of the kernel, only -n (network) will work."""))
parser.add_argument("--command", "-c", dest="command", type=str, default=["bash"], nargs="+",
        help=_("Run specific command in container (command as argument)"))
parser.add_argument("--home", "-h", dest="home", action="store_true",
        help=_("Use real home directory instead of copy-on-write"))
parser.add_argument("--network", "-n", dest="network", action="store_true",
        help=_("Enable networking in the container"))
parser.add_argument("--size", "-s", dest="size", type=int, default=None, nargs=1,
        help=_("Storage size in MB (default: 2000 on ext4, 50%% of RAM on tmpfs)"))
parser.add_argument("--type", "-t", dest="type", type=str, choices=("ext4","tmpfs"),
        help=_("Storage type. Supported values: ext4, tmpfs (default: ext4)"),default="ext4")
parser.add_argument("--tmp", "-T", dest="tmp", action="store_true",
        help=_("Use real /tmp directory instead of copy-on-write"))

parser.add_argument("--help",action="store_true")

args = parser.parse_args()
if args.help:
    parser.print_help()
    sys.exit(0)

# Start the container
bind=[]
if args.home:
    bind.append(os.getenv("HOME"))
if args.tmp:
    bind.append("/tmp")

if args.size:
    args.size=args.size[0]

# Get the current user
user=pwd.getpwuid(int(os.getenv("PKEXEC_UID",os.getenv("UID",1000))))

container=arkose.ArkoseContainer(fssize=args.size,fstype=args.type,network=args.network,bind=bind)
container.run_command("su %s -c \"%s\"" % (user.pw_name, " ".join(args.command)))
container.cleanup()
