// Google CacheBack
// version 0.1
// 2006-01-02
// Copyright (c) 2005, chocolateboy
// Released under the GPL license
// http://www.gnu.org/copyleft/gpl.html
//
// --------------------------------------------------------------------
//
// This is a Greasemonkey user script. To install it, you need
// Greasemonkey 0.3 or later: http://greasemonkey.mozdev.org/
// Then restart Firefox and revisit this script.
// Under Tools, there will be a new menu item to "Install User Script".
// Accept the default configuration and install.
//
// To uninstall, go to Tools/Manage User Scripts,
// select "Google CacheBack", and click Uninstall.
//
// --------------------------------------------------------------------
//

// ==UserScript==
// @name        Google CacheBack
// @namespace   http://www.chocolatey.com/code/js
// @description Detects Google cache misses, and redirects to a less forgetful data centre, or, failing that, to archive.org
// @include     http://*/search?q=cache:*
// ==/UserScript==

const FAILOVER_IP = '216.239.57.98';

var matches = window.location.href.match(/\?q=cache:([^:]+):([^+]+)/);
var id = matches[1];
var original_url = matches[2];
var data_centre = new RegExp('^http:\/\/' + window.location.host.replace(/\./g, '\\.') + '/');
var cached = new RegExp('\\?q=cache:' + id);
var failover = window.location.host == FAILOVER_IP ?
    'http://web.archive.org/web/*/' + original_url :
    window.location.href.replace(data_centre, 'http://' + FAILOVER_IP + '/');

if (!(cached.test(document.body.textContent))) {
    window.location.replace(failover);
}
