#!/usr/bin/python

import sys, os
if 'GEET_DEBUG' in os.environ:
    program_path = sys.path[0]
    sys.path.insert(0, os.path.join(program_path, 'modules'))
from geet_client import BoxManager
import geet_client.option_parser as option_parser

help="""
geet-box create <name> [<options>]
geet-box remove <name>
geet-box search <pattern>
geet-box options <name> [<options>]

<options> is
    <key>=<value>
or
    <key>=<value1>,<value2>...

Last form can remove options with
    -<key>
or modify lists of values
    <key>+=<value1>,<value2>...
or
    <key>-=<value1>,<value2>...

Valid options:
env - boxes witch will be used for build
archs - all architectures, set automatically do not modify it by this command
flavours - all flavours
flavour - flavour for package
mailto - email addresses to send build reports
"""

def error_arguments():
    print help
    sys.exit(1)

if len(sys.argv) < 3:
    error_arguments()

name = sys.argv[2]

if sys.argv[1] == 'create':
    opts = {}
    for i in sys.argv[3:]:
        t = option_parser.Token(i)
        if t.t != option_parser.SET:
            error_arguments()
        opts[t.key] = t.value
    box = BoxManager().create(name)
    box.setOptions(opts)
elif sys.argv[1] == 'remove':
    BoxManager().remove(name)
elif sys.argv[1] == 'search':
    for box in BoxManager().search(sys.argv[2]):
        print box
elif sys.argv[1] == 'options':
    box = BoxManager().get(sys.argv[2])
    if len(sys.argv) == 3:
        print box.options()
    else:
        opts = box.options()
        for i in sys.argv[3:]:
            t = option_parser.Token(i)
            if t.t == option_parser.SET:
                opts[t.key] = t.value
            elif t.t == option_parser.UNSET:
                del opts[t.key]
            elif t.t == option_parser.APPEND:
                if t.key in opts:
                    vals = opts[t.key].split(',')
                else:
                    vals = []
                opts[t.key] = ','.join(set(vals + t.values))
            elif t.t == option_parser.REMOVE:
                vals = opts[t.key].split(',')
                for i in t.values:
                    vals.remove(i)
                opts[t.key] = ','.join(vals)
            else:
                error_arguments()
        box.setOptions(opts)
else:
    error_arguments()
