#include <CoreServices/CoreServices.h>
#include <Quartz/Quartz.h>
#include <getopt.h>
/*
	Usage: PDFPassword inputfile outputfile password
	
	password = [ownerpassword]:[userpassword]
*/

void showHelp();
void showUsage();

int main (int argc, char * const argv[]) {

	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	
	int ch;
	int returnValue = 11;

	NSString *inputPath = NULL;
	NSString *outputPath = NULL;
	NSString *userPassword = NULL;
	NSString *ownerPassword = NULL;
	bool isPermitPrinting = true;
	bool isPermitCopying = true;
	bool isDebug = false;

     /* options descriptor */
     static struct option longopts[] = {
			{ "sourcePDFFile",		required_argument,	NULL,	'i' },
			{ "convertedPDFFile",   required_argument,	NULL,	'o' },
			{ "author",				required_argument,	NULL,	'a' },
			{ "creator",			required_argument,	NULL,	'k' },
			{ "title",				required_argument,	NULL,	't' },
			{ "userPassword",		required_argument,	NULL,	'u' },
			{ "ownerPassword",		required_argument,	NULL,	'x' },
			{ "permitPrinting",		required_argument,	NULL,	'p' },
			{ "permitCopying",		required_argument,	NULL,	'c' },
			{ "debug",				no_argument,		NULL,	'd' },
			{ "help",				no_argument,		NULL,	'h' },
			{ NULL,					0,					NULL,	0 }
     };

/*
CFStringRef kCGPDFContextAuthor;
CFStringRef kCGPDFContextCreator;
CFStringRef kCGPDFContextTitle;
CFStringRef kCGPDFContextOwnerPassword;
CFStringRef kCGPDFContextUserPassword;
CFStringRef kCGPDFContextAllowsPrinting;
CFStringRef kCGPDFContextAllowsCopying;
CFStringRef kCGPDFContextOutputIntent;
CFStringRef kCGPDFContextOutputIntents;
*/
	NSString *optValue;
	
//	NSDictionary *options = NULL;
	NSMutableDictionary *options = [ NSMutableDictionary dictionaryWithCapacity:10 ];

	while ((ch = getopt_long(argc, argv, "i:o:a:k:t:u:x:p:c:dh", longopts, NULL)) != -1)
		switch (ch) {
			case 'i':
				inputPath = [[NSString stringWithCString: optarg encoding: NSUTF8StringEncoding] stringByExpandingTildeInPath];
				break;
			case 'o':
				outputPath = [[NSString stringWithCString: optarg encoding: NSUTF8StringEncoding] stringByExpandingTildeInPath];
				break;
			case 'a':
				[ options setValue:	[NSString stringWithCString: optarg encoding: NSUTF8StringEncoding]
							forKey:		(void *)kCGPDFContextAuthor ];
				break;
			case 'k':
				[ options setValue:	[NSString stringWithCString: optarg encoding: NSUTF8StringEncoding]
						forKey:	(void *)kCGPDFContextCreator ];
				break;
			case 't':
				[ options setValue:	[NSString stringWithCString: optarg encoding: NSUTF8StringEncoding]
						forKey:	(void *)kCGPDFContextTitle ];
				break;
			case 'u':
				userPassword = [NSString stringWithCString: optarg encoding: NSUTF8StringEncoding];
				[ options setValue:userPassword forKey:(void *)kCGPDFContextUserPassword ];
				break;
			case 'x':
				ownerPassword = [NSString stringWithCString: optarg encoding: NSUTF8StringEncoding];
				[ options setValue:ownerPassword forKey:(void *)kCGPDFContextOwnerPassword ];
				break;
			case 'p':
				optValue = [NSString stringWithCString: optarg encoding: NSUTF8StringEncoding];
				if ( ( [optValue caseInsensitiveCompare:@"YES"] == NSOrderedSame )
					|| ( [optValue caseInsensitiveCompare:@"TRUE"] == NSOrderedSame )
					|| ( [optValue caseInsensitiveCompare:@"1"] == NSOrderedSame ) )	{
					isPermitPrinting = true;
					[ options setValue:	[NSNumber numberWithBool: isPermitPrinting] 
						forKey:	(void *)kCGPDFContextAllowsPrinting ];
				}
				else if ( ( [optValue caseInsensitiveCompare:@"NO"] == NSOrderedSame )
					|| ( [optValue caseInsensitiveCompare:@"FALSE"] == NSOrderedSame )
					|| ( [optValue caseInsensitiveCompare:@"0"] == NSOrderedSame ) )	{
					isPermitPrinting = false;
					[ options setValue:	[NSNumber numberWithBool: isPermitPrinting]
						forKey:	(void *)kCGPDFContextAllowsPrinting ];
				}
				break;
             case 'c':
				optValue = [NSString stringWithCString: optarg encoding: NSUTF8StringEncoding];
				if ( ( [optValue caseInsensitiveCompare:@"YES"] == NSOrderedSame )
					|| ( [optValue caseInsensitiveCompare:@"TRUE"] == NSOrderedSame )
					|| ( [optValue caseInsensitiveCompare:@"1"] == NSOrderedSame ) )	{
					isPermitCopying = false;
					[ options setValue:	[NSNumber numberWithBool: isPermitCopying]
						forKey:	(void *)kCGPDFContextAllowsCopying ];
				}
				if ( ( [optValue caseInsensitiveCompare:@"NO"] == NSOrderedSame )
					|| ( [optValue caseInsensitiveCompare:@"FALSE"] == NSOrderedSame )
					|| ( [optValue caseInsensitiveCompare:@"0"] == NSOrderedSame ) )	{
					isPermitCopying = false;
					[ options setValue:	[NSNumber numberWithBool: isPermitCopying] 
						forKey:	(void *)kCGPDFContextAllowsCopying ];
				}
				break;
             case 'h':
				showHelp();
				returnValue = 4;
				goto Exit;
				break;
             case 'd':
				isDebug = YES;
				break;
             default:
				showUsage();
				returnValue = 5;
				goto Exit;
				break;
     }

	if ( ( inputPath == NULL ) || ( outputPath == NULL ) )	{
		printf("You have to specify the source PDF file and converted file.\n");
		showUsage();
		returnValue = 1;
		goto Exit;
	}

	if ( ( [ ownerPassword length] == 0 ) && ( [ userPassword length] != 0 ) )
		[ options setValue:@"" forKey:	(void *)kCGPDFContextOwnerPassword ];

	if ( isDebug )	CFShow(options);

	PDFDocument *pdfDoc = [[PDFDocument alloc] initWithURL: [NSURL fileURLWithPath: inputPath ] ];
	if ( pdfDoc == NULL )	{
		returnValue = 2;
		printf("Input File is not valid.");
		goto Exit;
	}
	if ( ! [pdfDoc writeToFile: outputPath withOptions: options] )	{
		returnValue = 3;
		printf("Error in writing PDF file.");
		goto Exit;
	}
	
	returnValue = 0;
Exit:
	[pool release];

    return returnValue;
}

void showUsage()	{
	printf( "Please check the help message by 'pdfauxinfo --help'.\n\n" );
}

void showHelp()	{
	printf("Description:\n  pdfauxinfo can set the auxiliary information to PDF file using PDFKit in Cocoa.\n\nParameters:\n  --sourcePDFFile, -i Input_File_Path            Original PDF File.\n  --convertedPDFFile, -o Output_File_Path        Converted PDF File.\n  --author, -a Author_Name                       Author info of PDF.\n  --creator, -k Creator_Name                     Creator info of PDF.\n  --title, -t Title_of_Document                  Title of PDF.\n  --userPassword, -u User_Password               User Password for document.\n  --ownerPassword, -x Owner_Password             Owner Password for document.\n  --permitPrinting, -p [YES|true|1|NO|false|0]   Permission for printing the document.\n  --permitCopying, -c  [YES|true|1|NO|false|0]   Permission for copying the text.\n  --debug, -d                                    Debug mode.\n  --help, -h                                     Show this message.\n\nFor the option permitPrinting and permitCopying, YES or true or 1 means permitting, \nthe others means not permitting.\n\nYou need to specify the sourcePDFFile and convertedPDFFile options.\n\npdfauxinfo works just only Mac OS X Tiger or later.\n\n");
}