/*
 *  Region X Tool.c
 *
 */

#include "Region X Tool.h"

static UInt32 zOSVersion;								// OS X Version (not the z/OS version, haha)

int main(int argc, char **argv)
{
	OSStatus theErr;
	SInt32 OSVersion, OSMajor, OSMinor, OSBugFix;

	theErr = Gestalt(gestaltSystemVersionMajor, &OSMajor);
	if (theErr == noErr) theErr = Gestalt(gestaltSystemVersionMinor, &OSMinor);
	if (theErr == noErr) theErr = Gestalt(gestaltSystemVersionBugFix, &OSBugFix);
	if (theErr == noErr)
	{
		zOSVersion = OSMajor*10000 + OSMinor*100 + OSBugFix;
	}
	else
	{
		// Some OS X versions (e.g. 10.3) have no gestaltSystemVersionMajor/Minor/BugFix, fallback to gestaltSystemVersion
		theErr = Gestalt(gestaltSystemVersion, &OSVersion);
		if (theErr == noErr)
		{
			OSMajor  = ((OSVersion>>12) * 10) + ((OSVersion>>8) & 0xf); // convert e.g. 0x10.. to 10
			OSMinor  = (OSVersion>>4) & 0xf;
			OSBugFix = OSVersion & 0xf;
			zOSVersion = OSMajor*10000 + OSMinor*100 + OSBugFix;
		}
		else
		{ // Probably a very old unsupported version...
			zOSVersion = 0;
		}
	}

// Now the real main code
	if ((argc == 2) && !strcmp(argv[1], REGION_X_TOOL_REPAIR))
	{
		chown(argv[0], 0, 0);
		chmod(argv[0], S_ISUID|S_ISGID|S_IRUSR|S_IXUSR|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH);
	}
	else
	{
		SetOFVariable(OFREGIONCODE, argv[1]);
		SetOFVariable(OFREGIONCHANGE, argv[2]);
		
		// Then, if requested and possible, remove the variables.
		if ((argc == 4) && !strcmp(argv[3], REGION_X_TOOL_DELETE))
		{
			if (zOSVersion >= 100400) // 1.6: OS X < 10.4 does not support kIONVRAMDeletePropertyKey 
			{
				DeleteOFVariable(OFREGIONCODE);
				DeleteOFVariable(OFREGIONCHANGE);
			}
		}
	}

	
	return 0;
}
