{ pkgs, user, config, ... }:

let
  startpageDir = import ../startpage/dir.nix;
  startpage = "file:///${config.home.homeDirectory}/${startpageDir}/index.html";
  firefox-csshacks = pkgs.fetchFromGitHub {
    owner = "MrOtherGuy";
    repo = "firefox-csshacks";
    rev = "76867a5f570319d1bfd8cd396c92c876450328da";
    sha256 = "pGDnT1aRsu/06dlYtsHLkaNakfvXmQQ/SAplClyS/2c=";
  };
in
{
  nixpkgs = {
    config.allowUnfree = true;
    overlays = [
      (self: super: {
        firefox = super.firefox.overrideAttrs (oa: {
          buildCommand = oa.buildCommand + ''
            cd lib/firefox
            mkdir -p defaults/pref
            cat > defaults/pref/autoconfig.js << 'EOL'
            //
            pref("general.config.filename", "autoconfig.cfg");
            pref("general.config.obscure_value", 0);
            pref("general.config.sandbox_enabled", false);
            EOL
            cat > autoconfig.cfg << 'EOL'
            //
            var {classes:Cc,interfaces:Ci,utils:Cu} = Components;  
              
            /* set new tab page */  
            try {  
              Cu.import("resource:///modules/AboutNewTab.jsm");  
              var newTabURL = "${startpage}";
              AboutNewTab.newTabURL = newTabURL;  
            } catch(e){Cu.reportError(e);} // report errors in the Browser Console  
            EOL
          '';
        });
      })
    ];
  };

  programs.firefox = {
    enable = true;
    profiles.${user} = {
      isDefault = true;
      settings = {
        "browser.startup.homepage" = "${startpage}";
        "toolkit.legacyUserProfileCustomizations.stylesheets" = true;
        "browser.backspace_action" = 0;
        "extensions.unifiedExtensions.enabled" = false;
      };
      userChrome = builtins.readFile "${firefox-csshacks}/chrome/autohide_toolbox.css";
    };
  };
}
