#!/usr/bin/env python3

import os
import sys
import argparse
from string import Formatter

INIT_NOVOL = 'docker run -td --name={envname} {image} /bin/bash'
INIT       = 'docker run -td --name={envname} -v {hostvol}:{dstvol} {image} /bin/bash'
ATTACH     = 'docker exec -it --privileged {envname} /bin/bash'
ATTACH_CMD = 'docker exec -it --privileged {envname} {cmd}'

def new(args):
    if args.novol:
        stmt = Formatter().vformat(INIT_NOVOL, (), vars(args))
    else:
        if args.hostvol:
            if not os.path.isdir(args.hostvol):
                print(args.hostvol, "is not a directory or doesn't exist.", file=sys.stderr)
                exit(1)
        args.hostvol = os.path.join(os.getcwd(), args.hostvol or args.envname)
        if not os.path.exists(args.hostvol):
            os.mkdir(args.hostvol)
        stmt = Formatter().vformat(INIT, (), vars(args))
    print(stmt, file=sys.stderr)
    os.system(stmt)

def run(args):
    stmt = Formatter().vformat(ATTACH, (), vars(args))
    print(stmt, file=sys.stderr)
    os.system(stmt)

def list(args):
    pass

actions = {f.__name__: f for f in [new, run]}

def main():
    parser = argparse.ArgumentParser(description="CTF environments manage tool")
    subparsers = parser.add_subparsers(title='Actions', dest='action', required=True)

    parser_new = subparsers.add_parser('new', help='Create a new environment')
    parser_new.add_argument("envname", help='Name of the new environment')
    parser_new.add_argument("image", help="Tag of the image to run")
    parser_new.add_argument("--hostvol", metavar="PATH", \
            help="Volume to mount. Creates a direcotry [envname] and mount it if not set.")
    parser_new.add_argument("--mountto", metavar="PATH", dest='dstvol', default='/mnt', \
            help="Container mountpoint. Defaults to /mnt.")
    parser_new.add_argument("--no-vol", action='store_true', dest='novol', \
            help="No volumes. This overrides any other volume options.")

    parser_run = subparsers.add_parser('run', help='Attach to an existing environment')
    parser_run.add_argument("envname", help="Name of the environment to be attached.")

    args = parser.parse_args()
    actions[args.action](args)


if __name__ == '__main__':
    main()
