
const Cc = Components.classes;
const Ci = Components.interfaces;
Components.utils.import("resource://gre/modules/FileUtils.jsm");
Components.utils.import("resource://gre/modules/NetUtil.jsm");
Components.utils.import('resource://gre/modules/XPCOMUtils.jsm');
Components.utils.import('resource://gre/modules/Services.jsm');

XPCOMUtils.defineLazyServiceGetter(this, 'UsAgent', '@mozilla.org/network/protocol;1?name=http', 'nsIHttpProtocolHandler');

const uSOverride		=	'general.useragent.override';
const uSString			=	"kmeleon.privacy.useragent";

function nsKmeleonMain() {
	this.wrappedJSObject = this;
	this.prefs = Cc['@mozilla.org/preferences-service;1'].getService(Ci.nsIPrefService).getBranch(null);
}
nsKmeleonMain.prototype = {
classID:	Components.ID('{FD1A56FA-0A19-424f-8C9D-FBBFF7CFEB07}'),


userAgent: function(aSubject) {
	
	var prefs = Cc['@mozilla.org/preferences-service;1'].getService(Ci.nsIPrefService).getBranch(null),
	nsIChannel = aSubject.QueryInterface(Ci.nsIChannel), 
	nsIHttpChannel = aSubject.QueryInterface(Ci.nsIHttpChannel),
	NoUserAgent=prefs.getBoolPref(uSString+'.nouseragent'),
	Count=prefs.getIntPref(uSString+'.Count'),
	UrlHost=nsIChannel.URI.host;

		if(NoUserAgent){
		prefs.setCharPref(uSOverride, "");

		return;
			
		}
		
		if(Count != null){
			for (var i = 0; i < Count; i++) {
			var uaSites,j;
				j=i+1;
			uaSites=prefs.getCharPref(uSString+j+'.sites');
			if(uaSites.indexOf(UrlHost)>-1){
				var overrideString=prefs.getCharPref(uSString+j+'.string');
				prefs.setCharPref(uSOverride, overrideString);
				nsIHttpChannel.setRequestHeader('User-Agent', overrideString, false);
					return;


				}else{

			var KmOverrideString = 'Mozilla/5.0 (' + UsAgent.oscpu + '; ' + UsAgent.misc + ') Gecko/20140105 K-Meleon/74.0'  ;
			prefs.setCharPref(uSOverride, KmOverrideString);
			nsIHttpChannel.setRequestHeader('User-Agent', KmOverrideString, false);

			}
				
				
			}
			
		}




},
AddManifes: function(aTopic) {
	var ReloadManifes = function() {
		  let chromeReg = Components.classes["@mozilla.org/chrome/chrome-registry;1"].
                  getService(Components.interfaces.nsIChromeRegistry);
		  var uri = chromeReg.checkForNewChrome();

	}
			var timer = Cc['@mozilla.org/timer;1'].createInstance(Ci.nsITimer);
		timer.initWithCallback(ReloadManifes, 1000, Ci.nsITimer.TYPE_ONE_SHOT);

	if(aTopic=='profile-after-change'){
	 var result,data,path,Thepath,theData='',mods=null;
	 path = Cc["@mozilla.org/file/directory_service;1"]
			.getService(Ci.nsIProperties)
			.get("GreD", Ci.nsILocalFile);
	 Thepath=path.path+'\\extensions';
	 var file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile);

	 file.initWithPath(Thepath);
	 file.append("extensions.manifest");
	if(!file.exists()){
	file.create(Ci.nsIFile.NORMAL_FILE_TYPE, FileUtils.PERMS_FILE);
	}
	function EditManifest(data){
	var foStream = Cc["@mozilla.org/network/file-output-stream;1"].
		       createInstance(Ci.nsIFileOutputStream);
	foStream.init(file, 0x02 | 0x08 | 0x20, 0666, 0); 
	foStream.write(data, data.length);
	}
	var folder = Cc["@mozilla.org/file/local;1"]
		.createInstance(Ci.nsILocalFile);
	mods = [];
	amods = [];
	dum='';
	function ManifestList(MYpath, aArray,FolderName){
	folder.initWithPath(MYpath);

			if (folder.isDirectory()) {
				var name,afile,files = folder.directoryEntries;
				while (files.hasMoreElements()) {
					afile = files.getNext();
						if (afile instanceof Ci.nsILocalFile){

							if (afile.isDirectory()) {
							name = afile.leafName.toLowerCase();
			aArray[aArray.length] = name;
							}
							if (afile.isFile()) {
							name = afile.leafName.toLowerCase();

								if ((name != "extensions.manifest") && (name.substr(name.lastIndexOf(".")) == ".manifest")){
									
								var prantpath="\nmanifest ";
								if (FolderName.length > 1){	
								prantpath="\nmanifest "+FolderName+"\\";
								 }
																						theData=theData+prantpath+name;
								}
							}
						}
				}
				EditManifest(theData);
			}
			
		}
		ManifestList(Thepath,mods,dum);
		var counter=mods.length;
		while (counter > -1) {
		var newPath=Thepath+"\\"+mods[counter-1];
		ManifestList(newPath,amods,mods[counter-1]);
		counter=counter-1;
		}	
		
	}

},
observe: function(aSubject, aTopic, aData) {
	try {
		switch (aTopic) {
			case 'app-startup'						:	this.Startup();			break;
			case 'profile-after-change'				:	this.AddManifes(aTopic);	break;
			case 'http-on-modify-request'			:	this.userAgent(aSubject);	break;
			case 'xpcom-shutdown'					:	this.Shutdown();		break;
		}
	} catch (err) {}
},
get Shutdown() {
	Services.obs.removeObserver(this, 'profile-after-change');
	Services.obs.removeObserver(this, 'http-on-modify-request');
	Services.obs.removeObserver(this, 'xpcom-shutdown');
},
get Startup() {
	Services.obs.addObserver(this, 'xpcom-shutdown', false);
	Services.obs.addObserver(this, 'http-on-modify-request', false);
	Services.obs.addObserver(this, 'profile-after-change', false);
},
QueryInterface:		XPCOMUtils.generateQI([Ci.nsIObserver]),
_xpcom_categories: [{ category: 'app-startup' }]
};

const NSGetFactory = XPCOMUtils.generateNSGetFactory([nsKmeleonMain]);