/*
 * BEGIN COPYRIGHT BLOCK
 * Copyright (C) 2005 Red Hat, Inc.
 * All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation version
 * 2.1 of the License.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 * END COPYRIGHT BLOCK
 */
/*
 * retireveSIE.c: test program to test an API getServerDNList
 * Usage: retireveSIE configdir
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "libadminutil/admutil.h"
#include "libadminutil/distadm.h"
#include "libadminutil/srvutil.h"

int
main(int ac, char **av)
{
    int _ai=ADMUTIL_Init();
    AdmldapInfo ldapInfo = NULL;
    AttrNameList nameList = NULL;
    char *configdir = NULL;
    char *userdn;
    int rval = 0;
    char **p;
    int siecnt = 0;

    (void)_ai;
    if (ac > 1) {
        configdir = strdup(*(av+1));
    }
    
    if (NULL == configdir || 0 == strlen(configdir)) {
        fprintf(stderr, "ERROR: config dir was not specified.\n");
        exit(1);
    } else {
        fprintf(stdout, "%s: configdir: %s\n", *av, configdir);
    }

    /*
     * get the LDAP information from admin server config info
     */
    ldapInfo = admldapBuildInfo(configdir, &rval);
    if (NULL == ldapInfo) {
        fprintf(stderr, "ERROR: empty ldapInfo\n");
        rval = 1;
        goto done;
    }

    if (ADM_GetUserDNString(&rval, &userdn) || !userdn) {
        fprintf(stderr, "ERROR: could not get current userdn %d\n", rval);
        goto done;
    }
    /* override - cannot use siedn any more for auth */
    admldapSetSIEDN(ldapInfo, userdn);

    /*
     * get servers' DNs belonging to the Admin Server
     */
    nameList = getServerDNList(ldapInfo);
    destroyAdmldap(ldapInfo);
    if (NULL == nameList) {
        fprintf(stderr, "ERROR: empty nameList\n");
        rval = 1;
        goto done;
    }

    for (p = nameList; p && *p; p++) {
        fprintf(stdout, "%s\n", *p);
        if (0 == strncasecmp(*p, "cn=", 3)) {
            siecnt++;
        }
    }
    deleteAttrNameList(nameList);
    if (siecnt > 0) {
        fprintf(stdout, "SUCCESS: SIE%s retrieved\n",  siecnt>1?"S are":" is");
    } else {
        fprintf(stdout, "FAILURE: SIE is not retrieved\n");
    }

done:
    exit(rval);
}
