#import <Cocoa/Cocoa.h>
#include <spawn.h>
#include <stdlib.h>
#include <unistd.h>

extern char **environ;

@interface AppDelegate : NSObject <NSApplicationDelegate>
@property (nonatomic, assign) BOOL handledOpen;
@end

@implementation AppDelegate

- (void)spawnPosprintWithArg:(NSString *)arg {
    NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
    NSString *binPath = [bundlePath stringByAppendingPathComponent:@"Contents/MacOS/posprint-bin"];
    const char *bin = [binPath fileSystemRepresentation];

    pid_t pid;
    if (arg != nil) {
        const char *cArg = [arg UTF8String];
        char *const argv[] = { (char *)bin, (char *)cArg, NULL };
        posix_spawn(&pid, bin, NULL, NULL, argv, environ);
    } else {
        char *const argv[] = { (char *)bin, NULL };
        posix_spawn(&pid, bin, NULL, NULL, argv, environ);
    }
}

- (void)application:(NSApplication *)application openURLs:(NSArray<NSURL *> *)urls {
    self.handledOpen = YES;
    for (NSURL *url in urls) {
        if ([url isFileURL]) {
            [self spawnPosprintWithArg:[url path]];
        } else {
            [self spawnPosprintWithArg:[url absoluteString]];
        }
    }
    _exit(0);
}

- (void)applicationDidFinishLaunching:(NSNotification *)notification {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(80 * NSEC_PER_MSEC)), dispatch_get_main_queue(), ^{
        if (!self.handledOpen) {
            [self spawnPosprintWithArg:nil];
        }
        _exit(0);
    });
}

@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        if (argc > 1) {
            NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
            NSString *binPath = [bundlePath stringByAppendingPathComponent:@"Contents/MacOS/posprint-bin"];
            const char *bin = [binPath fileSystemRepresentation];
            char **newArgv = calloc((size_t)argc + 1, sizeof(char *));
            newArgv[0] = (char *)bin;
            for (int i = 1; i < argc; i++) {
                newArgv[i] = (char *)argv[i];
            }
            newArgv[argc] = NULL;
            pid_t pid;
            posix_spawn(&pid, bin, NULL, NULL, newArgv, environ);
            free(newArgv);
            return 0;
        }
        NSApplication *app = [NSApplication sharedApplication];
        AppDelegate *delegate = [[AppDelegate alloc] init];
        [app setDelegate:delegate];
        [app run];
    }
    return 0;
}
