/*******************************************************************************
 *	Boapnsc.cc	Boap Name Server Client
 *			T.Barnaby,	BEAM Ltd,	4/3/05
 *******************************************************************************
 */
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <BString.h>
#include <iostream>
#include <BoapnsC.h>

int usage(){
	fprintf(stderr, "Usage: boapnsc [options]\n");
	fprintf(stderr, "	-a		- List all entries\n");
	fprintf(stderr, "	-l <name>	- Find entry for named object\n");
	return 1;
}

void entryPrint(Boapns::BoapEntry entry){
	BIter		i;
	BString		al;
	
	for(entry.addressList.start(i); !entry.addressList.isEnd(i); entry.addressList.next(i)){
		if(al.len())
			al = al + ",";
		al = al + entry.addressList[i];
	}
	
	printf("%-16.16s %s:%d %d (%s)\n", entry.name.retStr(), entry.hostName.retStr(), entry.port, entry.service, al.retStr());
}

int main(int argc, char** argv){
	Boapns::Boapns			boapns("boapns");
	int				a;
	BError				err;
	BString				name;
	Boapns::BoapEntry		entry;
	BList<Boapns::BoapEntry>	entryList;
	BIter				i;
	int				flagListAll = 0;
	
	for(a = 1; a < argc; a++){
		if(argv[a][0] == '-'){
			switch(argv[a][1]){
			case 'a':	flagListAll = 1;	break;
			case 'l':	name = argv[++a];	break;
			default:	exit(usage());
			}
		}
	}

	if(flagListAll){
		if(! (err = boapns.getEntryList(entryList))){
			for(entryList.start(i); !entryList.isEnd(i); entryList.next(i)){
				entryPrint(entryList[i]);
			}
		}
	}
	else if(name != ""){
		if(! (err = boapns.getEntry(name, entry))){
			entryPrint(entry);
		}
	}

	if(err)
		fprintf(stderr, "Error: %s\n", err.getString().retStr());
	
	return err.getErrorNo();
}
