#include <stdio.h>

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

void
DXPrint(NSString* format, ...)
{
	va_list args;
	va_start(args, format);
	NSString* string = [[NSString alloc] initWithFormat:format arguments:args];
	va_end(args);
	fputs([string UTF8String], stdout);
	[string release];
}




NSDictionary* proxies;
BOOL proxyFound;

void
printUnset(NSString* env)
{
	DXPrint(@"unset %@\n", env);
}

void
printProxy(NSDictionary* proxies, NSString* proto)
{
	NSString* key = nil;
	NSString* env = [[proto lowercaseString] stringByAppendingString:@"_proxy"];

	key = [proto stringByAppendingString:@"Enable"];
	NSNumber* enabled = [proxies objectForKey:key];
	if(enabled == nil || [enabled intValue] != 1) {
		printUnset(env);
		return;
	}

	key = [proto stringByAppendingString:@"Proxy"];
	id host = [proxies objectForKey:key];
	if(host == nil) {
		printUnset(env);
		return;
	}

	key = [proto stringByAppendingString:@"Port"];
	id port = [proxies objectForKey:key];
	if(port == nil) {
		printUnset(env);
		return;
	}

	NSString* uriPrefix = nil;
	if(![proto isEqual:@"SOCKS"]) {
		uriPrefix = @"http://";
	} else {
		uriPrefix = @"socks://";
	}

	DXPrint(@"export %@='%@%@:%@'\n", env, uriPrefix, host, port);
	proxyFound = YES;
}

void
printExceptions(NSDictionary* proxies)
{
	id exceptions = [proxies objectForKey:@"ExceptionsList"];
	if(exceptions == nil || ![exceptions isKindOfClass:[NSArray class]] || !proxyFound) {
		printUnset(@"no_proxy");
		return;
	}

	DXPrint(@"export no_proxy='%@'\n", [exceptions componentsJoinedByString:@","]);
}

int
main()
{
	NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];

	proxies  = (NSDictionary*)SCDynamicStoreCopyProxies(nil);
	proxyFound = NO;
	printProxy(proxies, @"HTTP");
	printProxy(proxies, @"HTTPS");
	printProxy(proxies, @"FTP");
	printProxy(proxies, @"SOCKS");
	printExceptions(proxies);
	
	[pool release];
	return 0;
}

