/*
 * Copyright (C) 2006, 2007 Apple Inc.  All rights reserved.
 * Copyright (C) 2006 Graham Dennis.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer. 
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution. 
 * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
 *     its contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission. 
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#import <Cocoa/Cocoa.h>
#import <Sparkle/SUUpdater.h>
#import <objc/objc-runtime.h>

static void enableWebKitNightlyBehaviour() __attribute__ ((constructor));

static NSString *WKNERunState = @"WKNERunState";
static NSString *WKNEShouldMonitorShutdowns = @"WKNEShouldMonitorShutdowns";

typedef enum {
    RunStateShutDown,
    RunStateInitializing,
    RunStateRunning
} WKNERunStates;

static char *webKitAppPath;
static bool extensionBundlesWereLoaded = NO;
static NSSet *extensionPaths = nil;

// We need to tweak the wording of the prompt to make sense in the context of WebKit and Safari.
NSString* updatePermissionPromptDescription(id self, SEL _cmd)
{
    return @"Should WebKit automatically check for updates? You can always check for updates manually from the Safari menu.";
}

// -[SUBasicUpdateDriver downloadDidFinish:] requires that the download be served over SSL or signed
// using a public key.  We're not interested in dealing with that hassle just at the moment.
void skipSignatureVerificationInDownloadDidFinish(id self, SEL _cmd, id download)
{
    objc_msgSend(self, @selector(extractUpdate));
}

NSPanel *updateAlertPanel(id updateItem, id host)
{
    NSString *hostName = objc_msgSend(host, @selector(name));
    NSPanel *panel = NSGetInformationalAlertPanel([NSString stringWithFormat:@"Would you like to download and install %@ %@ now?", hostName, objc_msgSend(updateItem, @selector(displayVersionString))],
                                                  [NSString stringWithFormat:@"You are currently running %@ %@.", hostName, objc_msgSend(host, @selector(displayVersion))],
                                                  @"Install Update", @"Skip This Version", @"Remind Me Later");
    NSArray *subviews = [[panel contentView] subviews];
    NSEnumerator *e = [subviews objectEnumerator];
    NSView *view;
    while (view = [e nextObject]) {
        if (![view isKindOfClass:[NSButton class]])
            continue;

        NSButton *button = (NSButton *)view;
        [button setAction:@selector(webKitHandleButtonPress:)];
        if ([button tag] == NSAlertOtherReturn)
            [button setKeyEquivalent:@"\033"];
    }
    [panel center];
    return panel;
}

id updateAlertInitForAlertPanel(id self, SEL _cmd, id updateItem, id host)
{
    NSPanel *panel = updateAlertPanel(updateItem, host);
    [panel setDelegate:self];

    self = [self initWithWindow:panel];
    if (!self)
        return nil;

    [updateItem retain];
    [host retain];

    object_setInstanceVariable(self, "updateItem", (void*)updateItem);
    object_setInstanceVariable(self, "host", (void*)host);

    [self setShouldCascadeWindows:NO];

    return self;
}

@implementation NSAlert (WebKitLauncherExtensions)

- (void)webKitHandleButtonPress:(id)sender
{
    // We rely on the fact that NSAlertOtherReturn == -1, NSAlertAlternateReturn == 0 and NSAlertDefaultReturn == 1
    // to map the button tag to the corresponding selector
    SEL selectors[] = { @selector(remindMeLater:), @selector(skipThisVersion:), @selector(installUpdate:) };
    SEL selector = selectors[[sender tag] + 1];

    id delegate = [[sender window] delegate];
    objc_msgSend(delegate, selector, sender);
}

@end

static void myBundleDidLoad(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo)
{
    // Break out early if we have already detected an extension
    // if (extensionBundlesWereLoaded)
    //    return;

    NSBundle *bundle = (NSBundle *)object;
    NSString *bundlePath = [[bundle bundlePath] stringByAbbreviatingWithTildeInPath];
    NSString *bundleFileName = [bundlePath lastPathComponent];

    // Explicitly ignore SIMBL.bundle, as its only purpose is to load extensions
    // on a per-application basis.  It's presence indicates a user has application
    // extensions, but not that any will be loaded into Safari
    if ([bundleFileName isEqualToString:@"SIMBL.bundle"])
        return;

    // If the bundle lives inside a known extension path, flag it as an extension
    NSEnumerator *e = [extensionPaths objectEnumerator];
    NSString *path = nil;
    while (path = [e nextObject]) {
        if ([bundlePath length] < [path length])
            continue;

        if ([[bundlePath substringToIndex:[path length]] isEqualToString:path]) {
            NSLog(@"Extension detected: %@", bundlePath);
            extensionBundlesWereLoaded = YES;
            break;
        }
    }
}

static NSBundle *webKitLauncherBundle()
{
    NSString *executablePath = [NSString stringWithUTF8String:webKitAppPath];
    NSRange appLocation = [executablePath rangeOfString:@".app/" options:NSBackwardsSearch];
    NSString *appPath = [executablePath substringToIndex:appLocation.location + appLocation.length];
    return [NSBundle bundleWithPath:appPath];
}

static void initializeSparkle()
{
    // Override some Sparkle behaviour
    Method methodToPatch = class_getInstanceMethod(objc_getRequiredClass("SUUpdatePermissionPrompt"), @selector(promptDescription));
    methodToPatch->method_imp = (IMP)updatePermissionPromptDescription;

    methodToPatch = class_getInstanceMethod(objc_getRequiredClass("SUBasicUpdateDriver"), @selector(downloadDidFinish:));
    methodToPatch->method_imp = (IMP)skipSignatureVerificationInDownloadDidFinish;

    methodToPatch = class_getInstanceMethod(objc_getRequiredClass("SUUpdateAlert"), @selector(initWithAppcastItem:host:));
    methodToPatch->method_imp = (IMP)updateAlertInitForAlertPanel;

    SUUpdater *updater = [SUUpdater updaterForBundle:webKitLauncherBundle()];

    // Find the first separator on the Safari menu…
    NSMenu *applicationSubmenu = [[[NSApp mainMenu] itemAtIndex:0] submenu];
    int i = 0;
    for (; i < [applicationSubmenu numberOfItems]; i++) {
        if ([[applicationSubmenu itemAtIndex:i] isSeparatorItem])
            break;
    }

    // … and insert a menu item that can be used to manually trigger update checks.
    NSMenuItem *updateMenuItem = [[NSMenuItem alloc] initWithTitle:@"Check for WebKit Updates…" action:@selector(checkForUpdates:) keyEquivalent:@""];
    [updateMenuItem setTarget:updater];
    [applicationSubmenu insertItem:updateMenuItem atIndex:i];
    [updateMenuItem release];
}

static void myApplicationWillFinishLaunching(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo)
{
    CFNotificationCenterRemoveObserver(CFNotificationCenterGetLocalCenter(), &myApplicationWillFinishLaunching, NULL, NULL);
    CFNotificationCenterRemoveObserver(CFNotificationCenterGetLocalCenter(), &myBundleDidLoad, NULL, NULL);
    [extensionPaths release];
    extensionPaths = nil;

    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setInteger:RunStateRunning forKey:WKNERunState];
    [userDefaults synchronize];

    if (extensionBundlesWereLoaded)
        NSRunInformationalAlertPanel(@"Safari extensions detected",
                                     @"Safari extensions were detected on your system.  Extensions are incompatible with nightly builds of WebKit, and may cause crashes or incorrect behavior.  Please disable them if you experience such behavior.", @"Continue",
                                     nil, nil);

    initializeSparkle();
}

static void myApplicationWillTerminate(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo)
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setInteger:RunStateShutDown forKey:WKNERunState];
    [userDefaults synchronize];
}

extern char **_CFGetProcessPath() __attribute__((weak));

static void poseAsWebKitApp()
{
    webKitAppPath = strdup(getenv("WebKitAppPath"));
    if (!webKitAppPath || !_CFGetProcessPath)
        return;

    // Set up the main bundle early so it points at Safari.app
    CFBundleGetMainBundle();

    // Fiddle with CoreFoundation to have it pick up the executable path as being within WebKit.app
    char **processPath = _CFGetProcessPath();
    *processPath = NULL;
    setenv("CFProcessPath", webKitAppPath, 1);
    _CFGetProcessPath();

    // Clean up
    unsetenv("CFProcessPath");
    unsetenv("WebKitAppPath");
}

static void enableWebKitNightlyBehaviour()
{
    unsetenv("DYLD_INSERT_LIBRARIES");
    poseAsWebKitApp();

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    extensionPaths = [[NSSet alloc] initWithObjects:@"~/Library/InputManagers/", @"/Library/InputManagers/",
                                                    @"~/Library/Application Support/SIMBL/Plugins/", @"/Library/Application Support/SIMBL/Plugins/",
                                                    @"~/Library/Application Enhancers/", @"/Library/Application Enhancers/",
                                                    nil];
    NSArray *disabledInputManagers = [NSArray arrayWithObjects:@"Saft", nil];

    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *defaultPrefs = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:RunStateShutDown], WKNERunState,
                                                                            [NSNumber numberWithBool:YES], WKNEShouldMonitorShutdowns,
                                                                            disabledInputManagers, @"NSDisabledInputManagers", nil];
    [userDefaults registerDefaults:defaultPrefs];
    if ([userDefaults boolForKey:WKNEShouldMonitorShutdowns]) {
        WKNERunStates savedState = (WKNERunStates)[userDefaults integerForKey:WKNERunState];
        if (savedState == RunStateInitializing) {
            // Use CoreFoundation here as AppKit hasn't been initialized at this stage of Safari's lifetime
            CFOptionFlags responseFlags;
            CFUserNotificationDisplayAlert(0, kCFUserNotificationCautionAlertLevel,
                                           NULL, NULL, NULL,
                                           CFSTR("WebKit failed to open correctly"),
                                           CFSTR("WebKit failed to open correctly on your previous attempt. Please disable any Safari extensions that you may have installed.  If the problem continues to occur, please file a bug report at http://webkit.org/quality/reporting.html"), 
                                           CFSTR("Continue"), NULL, NULL, &responseFlags);
        }
        else if (savedState == RunStateRunning) {
            NSLog(@"WebKit failed to shut down cleanly.  Checking for Safari extensions.");
            CFNotificationCenterAddObserver(CFNotificationCenterGetLocalCenter(), &myBundleDidLoad,
                                            myBundleDidLoad, (CFStringRef) NSBundleDidLoadNotification,
                                            NULL, CFNotificationSuspensionBehaviorDeliverImmediately);
        }
    }
    [userDefaults setInteger:RunStateInitializing forKey:WKNERunState];
    [userDefaults synchronize];

    CFNotificationCenterAddObserver(CFNotificationCenterGetLocalCenter(), &myApplicationWillFinishLaunching,
                                    myApplicationWillFinishLaunching, (CFStringRef) NSApplicationWillFinishLaunchingNotification,
                                    NULL, CFNotificationSuspensionBehaviorDeliverImmediately);
    CFNotificationCenterAddObserver(CFNotificationCenterGetLocalCenter(), &myApplicationWillTerminate,
                                    myApplicationWillTerminate, (CFStringRef) NSApplicationWillTerminateNotification,
                                    NULL, CFNotificationSuspensionBehaviorDeliverImmediately);

    NSLog(@"WebKit %@ initialized.", [webKitLauncherBundle() objectForInfoDictionaryKey:@"CFBundleShortVersionString"]);

    [pool release];
}
