#!/usr/bin/env python

print "add is deprecated.  Use xadd instead.\n"
raise SystemExit

# $Id: add,v 1.13 2005/10/12 18:40:53 boincadm Exp $


#XXX TODO: add app should modify config.xml to add application-specific daemons

'''
add items to the BOINC database -- command-line interface.  See also ``xadd``.

Usages:

add project      --name=yah --long_name="YETI @ home"

add platform     --name=c64 [ --user_friendly_name="Commodore 64" ]

add core_version --platform=c64 --version_num=717
                    --exec_file=/path/to/boinc_7.17_c64
                    [--message="Message"] [--message_priority="Priority"]

add app          --name=YetiApp [--min_version=716]

add app_version  --app=YetiApp --platform=c64 --version_num=717
                    --exec_file=/path/to/yeti_7.17_c64
                      [--signature_file=/path/to/sig_file]
                    [--exec_file=/path/to/more_bins
                      [--signature_file=/tmp/sig_file2]] ...

add user         --name="Carl Sagan" --email_addr="carl.sagan@example.com"
                    --authenticator="deadbeef"
                    [--country=Estonia --postal_code=94703
                     --global_prefs_file=/path/to/prefs.xml]

add work         --name="/path/ap_20031026.23987.28452.wu"
                 --wu_template=/path/wu_template.xml
                 --result_template=/path/result_template.xml
                 [--rsc_fpops_est=3000000] [--rsc_fpops_bound=5000000]
                 [--rsc_memory_bound=20000000] [--rsc_disk_bound=10000000]
                 [--delay_bound=14days  | --delay_bound=1209600]
                 [--min_quorum=3]
                 [--target_nresults=10]
                 [--max_error_results=5]
                 [--max_total_results=20]
                 [--max_success_results=10]
                 [--sequence 4] (unimplemented)
                 infile1 [infile2] ...

add workunit  (TODO)

add result    (TODO) '''

import boinc_path_config
from Boinc import database, db_mid, configxml
from Boinc.util import *
from Boinc.add_util import *
import sys, os, getopt

def ambiguous_lookup(string, dict):
    results = []
    string = string.replace('_','')
    for key in dict:
        k = key.replace('_','')
        if k == string:
            return [dict[key]]
        if k.startswith(string):
            results.append(dict[key])
    return results

def lookup_object_to_add(name_of_object_to_add):
    name_of_object_to_add = name_of_object_to_add.strip().lower()
    possible_objects = ambiguous_lookup(name_of_object_to_add, add_objects)
    if len(possible_objects) == 0:
        raise SystemExit("No such object '%s' to add"%name_of_object_to_add)
    if len(possible_objects) > 1:
        print >>sys.stderr, "Object name '%s' matches multiple objects:"%name_of_object_to_add
        for object in possible_objects:
            print "    ", object.name
        raise SystemExit(1)
    return possible_objects[0]

def parse_global_options(args):
    # raise SystemExit('todo')
    pass

def dv(object,arg):
    if arg in object.default_values:
        return '    --%s [%s]' %(arg, object.default_values[arg])
    else:
        return '    --%s' %arg

def help_object(object, msg=None):
    if msg:
        print >>sys.stderr, "add:", msg
        print
    print >>sys.stderr, "Syntax: add %s"%object.name
    for arg in object.args:
        print >>sys.stderr, dv(object,arg)
    print >>sys.stderr, " Optional:"
    for arg in object.optional_args:
        print >>sys.stderr, dv(object,arg)
    raise SystemExit

def commandline_add_object(add_object, args):
    try:
        parsed_opts, placement_args = \
                     getopt.getopt(args, '',
                                   map(lambda s: s+'=',
                                       add_object.args + add_object.optional_args))
        if placement_args:
            raise getopt.GetoptError('Unknown args '+' '.join(placement_args))
    except getopt.GetoptError, e:
        help_object(add_object, e)
    untranslated_args_dict = {}
    for arg,value in parsed_opts:
        if not arg.startswith('--'):
            raise Exception('internal error: arg should start with "--"')
        untranslated_args_dict[arg[2:]] = value
    try:
        do_add_object(add_object, untranslated_args_dict)
    except AddObjectException, e:
        help_object(add_object, e)

if len(sys.argv) < 2:
    print >>sys.stderr, """Syntax: add <object_to_add> <options...>

Adds an object to the BOINC database.

Objects to add:"""
    for object in sorted_keys(objects_to_add):
        print >>sys.stderr, "    ", object
    print >>sys.stderr, """
Global options:
     --config=config.xml Path to configuration file.
     --skip_old          Ignore database objects that already exist

These override config.xml:
     --db_name           Database name
     --db_password       Database password
     --db_user           Database user

For command-line help on a particular object, use add <object> without further
arguments.
"""

    raise SystemExit(1)

add_object = lookup_object_to_add(sys.argv[1])

args = sys.argv[2:]
parse_global_options(args)

config = configxml.default_config()
database.connect(config.config)

commandline_add_object(add_object, args)
