/*
    1000 Bots - Surf the Web as Googlebot

    Copyleft (C) 2020 !Mediengruppe Bitnik, connect@bitnik.org

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

*/

'use strict';

var browser = browser || chrome
var user_agent = "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)";
var target_urls = "*://*/*";
var status = 0;


function set_extension_status_ON() {
    status = 1;
    //console.log('Setting status to ON');
    browser.browserAction.setIcon({path: 'icon_ON_48.png'});
    browser.browserAction.setTitle({title: "1000 Bots"});
}

function set_extension_status_OFF() {
    status = 0;
    //console.log('Setting status to OFF');
    browser.browserAction.setIcon({path: 'icon_OFF_48.png'});
    browser.browserAction.setTitle({title: "1000 Bots activate"});
}

function update_icon(){
    if(status == 0) {
        set_extension_status_ON();
    }else{
        set_extension_status_OFF();
    }
}


function rewrite_user_agent_header(e){
    
    //console.log('Browser http request!');

    if(status == 0) {
        // console.log('Nothing to do');
        return {requestHeaders: e.requestHeaders};
    }

    for (var header of e.requestHeaders) {
        if (header.name.toLowerCase() === "user-agent") {
            header.value = user_agent;
        }
      }
    //console.log('Set user-agent header to: ' + user_agent);
    return {requestHeaders: e.requestHeaders};

}


browser.runtime.onStartup.addListener(set_extension_status_OFF);
browser.browserAction.onClicked.addListener(update_icon);

browser.webRequest.onBeforeSendHeaders.addListener(
    rewrite_user_agent_header,
    {urls: [target_urls]},
    ["blocking", "requestHeaders"]
);
