#import <Foundation/Foundation.h>
#import <SystemConfiguration/SCDynamicStoreCopySpecific.h>

void
NSPrintF(NSString* file, NSString* format, ...)
{
	va_list args;
	va_start(args, format);
	NSString* string = [[NSString alloc] initWithFormat:format arguments:args];
	va_end(args);
	[string writeToFile:file atomically:NO encoding:NSUTF8StringEncoding error:nil];
	[string release];
}

void
NSPrint(NSString* format, ...)
{
	va_list args;
	va_start(args, format);
	NSString* string = [[NSString alloc] initWithFormat:format arguments:args];
	va_end(args);
	[string writeToFile:@"/dev/stdout" atomically:NO encoding:NSUTF8StringEncoding error:nil];
	[string release];
}


bool
printSystemConfiguration(bool quiet, NSString* keyName, NSDictionary* proxies)
{
	id value = [proxies objectForKey:keyName];
	if(nil != value) {
		NSArray* items;
		if([value isKindOfClass:[NSArray class]]) {
			items = value;
		} else {
			items = [NSArray arrayWithObjects:value, nil];
		}

		NSPrint([items componentsJoinedByString:@","]);
		NSPrint(@"\n");

	} else {
		if(!quiet) {
			NSPrintF(@"/dev/stderr", @"Value does not exist\n");
		}
		return FALSE; // Signal a fail condition
	}
	return TRUE;
}

void
printUsage(void)
{
	NSPrintF(@"/dev/stderr", @"sysconfig [-q] SystemConfigurationKeyName\n");
	exit(1);
}

int main(int argc, const char* argv[])
{
	NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
	NSDictionary* proxies = (NSDictionary*)SCDynamicStoreCopyProxies(nil);
	bool quiet = FALSE;
	NSString* keyName;

	if(2 == argc) {
		keyName = [NSString stringWithCString:argv[1]];
	} else if(3 == argc) {
		if(![[NSString stringWithCString:argv[1]] isEqualTo:@"-q"]) {
			printUsage();
		} else {
			quiet = TRUE;
		}

		keyName = [NSString stringWithCString:argv[2]];
	} else {
		printUsage();
	}

	if(!printSystemConfiguration(quiet, keyName, proxies)) {
		return 2;
	}
	
	[pool release];
	return 0;
}

