#!/usr/bin/env qore
# -*- mode: qore; indent-tabs-mode: nil -*-

%modern

%requires openldap
%requires LdapCli
%requires Util
%requires qore >= 2.3

main();

const AddOpts = CommonOpts + {
    "sep": "s,separator=s",
};

sub main() {
    GetOpt g(AddOpts);
    hash opts = g.parse3(\ARGV);

    Util::TerminalColor color(!opts.nocolor);

    if (opts.help) {
        usage(color);
    }

    handle_common_opts(opts, color);

    *string dn = shift ARGV;
    if (!dn) {
        ldap_error(color, "missing dn to add");
    }

    string sep = opts.sep ?? ",";
    if (sep.length() > 1) {
        ldap_error(color, "separator character can only be max 1 character long (value given: %y; size %d characters)", sep, sep.length());
    }

    # get attribute hash
    hash attr;
    while (ARGV) {
        string attrstr = shift ARGV;
        (*string key, auto val) = (attrstr =~ x/^([^=]+)=(.*)$/);
        if (!key) {
            ldap_error(color, "attribute not in <key>=<value> format: '%s'", attrstr);
        }
        if (attr{key}) {
            ldap_error(color, "attribute '%s' specified twice", key);
        }
        if (val && string(val).find(sep) != -1) {
            val = string(val).split(sep);
        }
        attr{key} = val;
    }
    if (!attr) {
        ldap_error(color, "missing attributes for '%s'", dn);
    }

    process_bind_password(\opts);
    string uri = get_uri(opts);
    hash lopt = opts{LdapOptionKeys};

    if (opts.verbose) {
        printf("%s %s\n", color.dim("uri:"), uri);
        printf("%s %s\n", color.dim("dn:"), dn);
        printf("%s %s\n", color.dim("attrs:"), color.formatValue(attr));
    }

    try {
        LdapClient ldap(uri, lopt);
        ldap.add(dn, attr);
        ldap_success(color, sprintf("added entry: %s", dn));
    } catch (hash<ExceptionInfo> ex) {
        ldap_error(color, "%s: %s", ex.err, ex.desc);
    }
}

sub usage(Util::TerminalColor color) {
    printf("%s %s [options] <dn> <attr>=<value> [...]\n\n", color.bold("usage:"), get_script_name());
    printf("%s\n", color.bold("Add Options:"));
    printf("  %s  %s\n", color.key(TerminalColor::padRight("-s,--separator=ARG", 22)), sprintf("list separator char %s", color.dim("(default: ',')")));
    printf("\n");
    print_common_usage(color);
    exit(0);
}
