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

%modern

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

main();

const ModifyOpts = CommonOpts + {
    "add": "a,add",
    "del": "x,delete",
};

sub main() {
    GetOpt g(ModifyOpts);
    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 modify");
    }

    if (opts.add && opts.del) {
        ldap_error(color, "can't use both -a (add) and -x (delete) options together");
    }

    string mod;
    if (opts.add) {
        mod = LDAP_MOD_ADD;
    } else if (opts.del) {
        mod = LDAP_MOD_DELETE;
    } else {
        mod = LDAP_MOD_REPLACE;
    }

    # get modification argument list
    list mods = ();
    while (ARGV) {
        *string attr = shift ARGV;
        if (!attr) {
            ldap_error(color, "missing attribute name in argument %d (starting with 0)", mods.size());
        }
        *string value = shift ARGV;
        if (!value) {
            ldap_error(color, "missing attribute value in argument %d (starting with 0)", mods.size());
        }
        # for delete: '-' means delete entire attribute
        if (opts.del && value == "-") {
            delete value;
        }
        mods += {"mod": mod, "attr": attr, "value": value};
    }

    if (mods.empty()) {
        ldap_error(color, "no modifications specified");
    }

    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("mods:"), color.formatValue(mods));
    }

    try {
        LdapClient ldap(uri, lopt);
        ldap.modify(dn, mods);
        ldap_success(color, sprintf("modified 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("Modify Options:"));
    printf("  %s  %s\n", color.key(TerminalColor::padRight("-a,--add", 22)), "add values (default is to replace)");
    printf("  %s  %s\n", color.key(TerminalColor::padRight("-x,--delete", 22)), sprintf("delete values; use %s to delete entire attribute", color.dim("'-'")));
    printf("\n");
    print_common_usage(color);
    exit(0);
}
