/*
    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;

const DEBUG = true; // Set to true to enable debug mode

// Duration to display the injected HTML (in milliseconds)
const DISPLAY_DURATION = 8000; // Set to 8 seconds

// Initialize storage for duration
browser.storage.sync.set(
	{ duration: DISPLAY_DURATION, debug: DEBUG },
	function () {
		if (browser.runtime.lastError) {
			console.error("Error setting duration:", browser.runtime.lastError);
		} else {
			if (DEBUG) console.log("Duration set to:", DISPLAY_DURATION);
		}
	}
);

// Inject the content.js script into all active tabs
function injectContentScript() {
	browser.tabs.query({}, (tabs) => {
		tabs.forEach((tab) => {
			// Check if the URL is not something like chrome:// or about:// etc.
			if (tab.url.startsWith("https://")) {
				browser.tabs.executeScript(
					tab.id,
					{ file: "content.js" },
					() => {
						if (browser.runtime.lastError) {
							console.error(
								`Error injecting content script into tab ${tab.id}:`,
								browser.runtime.lastError
							);
						} else {
							if (DEBUG)
								console.log(
									`Content script injected into tab ${tab.id}`
								);

							// If the duration has passed, removeInjectedContent
							const interval = setInterval(() => {
								browser.storage.sync.get(
									"duration",
									(result) => {
										if (browser.runtime.lastError) {
											console.error(
												"Error fetching duration:",
												browser.runtime.lastError
											);
										} else if (result.duration <= 0) {
											clearInterval(interval);
											removeInjectedContent();
										}
									}
								);
							});
						}
					}
				);
			} else {
				if (DEBUG)
					console.log(
						`Skipped injecting content script into tab ${tab.id} (chrome://, about:// URL or similar)`
					);
			}
		});
	});
}

// Remove the content from all active tabs
function removeInjectedContent() {
	browser.tabs.query({}, (tabs) => {
		tabs.forEach((tab) => {
			if (tab.url.startsWith("https://")) {
				browser.tabs.executeScript(
					tab.id,
					{
						code: `
                        const banner = document.querySelector('.extension-banner');
                        if (banner && banner.parentNode) {
                            banner.parentNode.removeChild(banner);
                        }
                    `,
					},
					() => {
						if (browser.runtime.lastError) {
							console.error(
								`Error removing injected content from tab ${tab.id}:`,
								browser.runtime.lastError
							);
						} else {
							if (DEBUG)
								console.log(
									`Removed injected content from tab ${tab.id}`
								);
						}
					}
				);
			} else {
				if (DEBUG)
					console.log(
						`Skipped removing injected content from tab ${tab.id} (chrome://, about:// URL or similar)`
					);
			}
		});
	});
}

// Function to refresh all active tabs
function refreshAllTabs() {
	browser.tabs.query({}, (tabs) => {
		tabs.forEach((tab) => {
			if (tab.url.startsWith("https://")) {
				browser.tabs.reload(tab.id, () => {
					if (browser.runtime.lastError) {
						console.error(
							`Error refreshing tab ${tab.id}:`,
							browser.runtime.lastError
						);
					} else {
						if (DEBUG) console.log(`Refreshed tab: ${tab.id}`);
					}
				});
			} else {
				if (DEBUG)
					console.log(
						`Skipped refreshing tab ${tab.id} (URL does not start with https://)`
					);
			}
		});
	});
}

function set_extension_status_ON() {
	status = 1;
	if (DEBUG) console.log("Setting status to ON");
	browser.browserAction.setIcon({ path: "icon_ON_48.png" });
	browser.browserAction.setTitle({
		title: "You are now surfing the web as a bot 🤖",
	});
	refreshAllTabs();

	setTimeout(() => {
		injectContentScript();
	}, 500);
}

function set_extension_status_OFF() {
	status = 0;
	if (DEBUG) console.log("Setting status to OFF");
	browser.browserAction.setIcon({ path: "icon_OFF_48.png" });
	browser.browserAction.setTitle({
		title: "Click here to refuse to be human 🤖",
	});
	removeInjectedContent();
	refreshAllTabs();
}

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

function rewrite_user_agent_header(e) {
	if (DEBUG) console.log("Browser http request!");

	if (status == 0) {
		if (DEBUG) 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;
		}
	}
	if (DEBUG) 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"]
);
