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

// Begin the nasty hack so that I can easily print out NSStrings to stdout
void fNSPrint(NSString * outputFilename, NSString * str)
{
	NSString * output = [NSString stringWithFormat:@"%@\n", str];
	[output writeToFile:outputFilename atomically:NO 
				encoding:NSUTF8StringEncoding error:nil];
}

void NSPrint(NSString *str)
{
	fNSPrint(@"/dev/stdout", str);
}

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

		NSEnumerator * enumerator = [itemsArray objectEnumerator];
		id item;
		while ((item = [enumerator nextObject]))
			NSPrint([NSString stringWithFormat:@"%@", item]);

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

void printUsage(void)
{
	fNSPrint(@"/dev/stderr", @"proxyconf [-q] SystemConfigurationKeyName");
}

int resolveSystemConfiguration(int argc, const char * argv[])
{
	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();
			return 1;
		} else {
			quiet = TRUE;
		}

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

	if (! printSystemConfiguration(quiet, keyName, proxies))
		return 2;

	return 0;
}

int main (int argc, const char * argv[])
{
	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

	int ret = resolveSystemConfiguration(argc, argv);
	
    [pool drain];
    return ret;
}
