/************************************************************************ 
  Copyright 2011-2012, IceJS Team. All rights reserved.
  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are
  met:
  
      * Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.
      * Redistributions in binary form must reproduce the above
        copyright notice, this list of conditions and the following
        disclaimer in the documentation and/or other materials provided
        with the distribution.
      * Neither the name of Update Freezer Team nor the names of its
        contributors may be used to endorse or promote products derived
        from this software without specific prior written permission.
  
  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ***********************************************************************/
 
if (typeof(g_executeInBatch) == "undefined")
{
	Include("Wrappers/Common.js")
	Include("Controllers/Controller.js");
}	

if (typeof(Scenario) == "undefined")
	Scenario = {};

	
Scenario.MozillaUpdater = 
{
	name: 			"Mozilla.Updater",
	displayName:    "Firefox",
	version: 		"1.0",
	description: 	"Checks if Mozilla Updater is enabled and allows to enable/disable update facilities",
	link:			"http://www.updatefreezer.org/index.php?id=22",
	icon:			"Resources/Mozilla.Updater.png",
	actions:		["query", "backup", "restore", "enable", "disable"],
		
	programs: [{path: "%PROGRAMFILES%\\Mozilla Firefox\\firefox.exe"},
	           {path: "%PROGRAMFILES%\\Mozilla Thunderbird\\thunderbird.exe"},
	           {path: "%PROGRAMFILES%\\mozilla.org\\SeaMonkey\\seamonkey.exe"},
	           {path: "%PROGRAMFILES%\\SeaMonkey\\seamonkey.exe"}],
	
	inherits: [ScenarioController],

//#region Implementation
	mozillaDataFileName: "Mozilla.Updater.json",

	config: "mozillaFreezer.cfg",
	localSettingsFile: "freezer-settings.js",
	localSettingsDir: "defaults\\pref\\",
	localSettingsPath: "defaults\\pref\\freezer-settings.js",
	
	products: 
	[
		{
			name: "Firefox",
			supported: true,
			procName: "firefox.exe",
			path: "%PROGRAMFILES%\\Mozilla Firefox\\"
		},
		{
			name: "Thunderbird",
			supported: false,
			procName: "thunderbird.exe",
			path: "%PROGRAMFILES%\\Mozilla Thunderbird\\"
		},
		{
			name: "Mozilla Suite",
			supported: false,
			path: "%PROGRAMFILES%\\mozilla.org\\Mozilla\\"
		},
		{
			name: "SeaMonkey 1.x",
			supported: false,
			procName: "seamonkey.exe",
			path: "%PROGRAMFILES%\\mozilla.org\\SeaMonkey\\"
		},
		{
			name: "SeaMonkey 2.0",
			supported: false,
			procName: "seamonkey.exe",
			path: "%PROGRAMFILES%\\SeaMonkey\\"
		}
	],
	
	ReadCfgFile: function(p, shift)
	{
		//var cfg = p + ".freezer";
		//if(Util.IO.ShiftFileBytes(p, cfg, shift))
		{
			var t = Util.IO.ReadFile(p);
			if(t.indexOf("//") == 0)
			{
				return t; // file decoded
			}
		}
		return Util.IO.ReadFile(p);
	},
	
	QueryMozillaProducts: function()
	{
		var result = 
		{
			products:[],
			exist: function()
			{
				return this.products.length > 0;
			},
			
			isEnabledProduct: function()
			{
				for(var i = 0; i < this.products.length; i++)
				{
					if (this.products[i].enabled)
						return true;
				}
				return false;
			}
		};	

		for(var i = 0; i < this.products.length; i++)
		{
			var p = this.products[i];
			if(!p.supported)
				continue;
			// check only installed products
			var fp = Util.Shell.ExpandEnvironmentString(p.path);
			var pc = Util.Process.GetProcessesCount(p.procName);
			if(pc > 0)
			{
				if(l1) Log1(SF("Mozilla.Updater.processRunning", [p.procName, true]));
			}
			
			if(Util.IO.CheckFileExists(fp))
			{
				// we do not check real settings here since they vary for each user.
				//search update settings in custom config instead
				var product = {
					"name": p.name,
					"procName": p.procName,
					"path": fp,
					"enabled": true,
					"autoUpdate": true,
					"state" : 0 // 0 - no config file, 1 - config file present, 2 - app.update.enabled lock present
				};
				var ls = fp + this.localSettingsPath;
				if(Util.IO.CheckFileExists(ls))
				{
					var ft = Util.IO.ReadFile(ls);
					var lsText = 'pref("general.config.filename", "' + this.config + '");\n';
					if(ft.indexOf(lsText) >= 0)
					{
						// only when config file set
						var cfg = fp + this.config;
						if(Util.IO.CheckFileExists(cfg))
						{
							product.state = 1;
							var t = this.ReadCfgFile(cfg, 13);
							var re = /^lockPref\([\s'\"]*app.update.enabled[\s'\"]*,[\s'\"]*(true|false)[\s'\"]*\);/im;
							var res = t.match(re);
							if (res != null && res.length > 1)
							{
								product.state = 2;
								if(res[1] == "false")
								{
									product.enabled = false;
								}
							}
							re = /^lockPref\([\s'\"]*app.update.auto[\s'\"]*,[\s'\"]*(true|false)[\s'\"]*\);/im;
							res = t.match(re);
							if (res != null && res.length > 1)
							{
								if(res[1] == "false")
								{
									product.autoUpdate = false;
								}
							}
						}
					}
				}
				result.products.push(product);
			}			
		}
		
		if(result.exist())
		{
			if(!result.isEnabledProduct())
			{
				queryResult.push({msg: S("Mozilla.Updater.ProductsDisabled")});
			}
			else
			{
				this.updaterEnabled = true;
				queryResult.push({msg: S("Mozilla.Updater.ProductsEnabled")});
			}
		}
		else
		{
			queryResult.push({msg: S("Mozilla.Updater.ProductsNotFound")});
		}

		var dataFileName =  Util.IO.CombinePath(this.dataFolderPath, this.mozillaDataFileName);
		Util.IO.WriteJsonToFile(dataFileName, result);
	},

	ChangeMozillaProducts: function(action)
	{
		var dataFileName =  Util.IO.CombinePath(this.dataFolderPath, this.mozillaDataFileName);
		var p = Util.IO.ReadJsonFromFile(dataFileName);
		if (p && p.products)
		{
			for(var i = 0; i < p.products.length; i++)
			{
				var product = p.products[i];
				var pc = Util.Process.GetProcessesCount(product.procName);
				if(pc > 0)
				{
					if(l1) Log1(SF("Mozilla.Updater.processRunning", [product.procName, true]));
				}

				var enabled = product.enabled;
				var auto = product.autoUpdate;
				switch(action)
				{
					case this.DISABLED: //1
						enabled = false;
						auto = false;
						break
					case this.NOTIFYONLY://2
						enabled = true;
						auto = false;
						break
					case this.AUTOMATIC://3
						enabled = true;
						auto = true;
						break;
					case this.NOTSET:
						this.RemoveFreezerOverride();
						return;
					case undefined:
						if(product.state < 2)
						{
							// no lock were before change, so we must remove lock
							this.RemoveFreezerOverride();
							return;
						}
						break;
				}
				this.SetProductState(product, enabled, auto);
				
				//tell the application to load the lock file. 
				//Create a new file in the defaults/pref subfolder of the installation directory.
				var lsText = 'pref("general.config.obscure_value", 0);\n';
				lsText += 'pref("general.config.filename", "' + this.config + '");\n';
				var ls = product.path + this.localSettingsPath;
				Util.IO.CreateDirectory(product.path + this.localSettingsDir);
				if(Util.IO.CheckFileExists(ls))
				{
					Util.IO.DeleteFile(ls);
				}
				Util.IO.WriteFile(ls, lsText);
			}
		}
	},
	
	RemoveFreezerOverride: function()
	{
		var p = Util.Shell.ExpandEnvironmentString("%PROGRAMFILES%\\Mozilla Firefox\\");
		if(Util.IO.CheckFileExists(p + this.config))
		{
			Util.IO.DeleteFile(p + this.config);
		}
		if(Util.IO.CheckFileExists(p + this.localSettingsPath))
		{
			Util.IO.DeleteFile(p + this.localSettingsPath);
		}
	},
	
	AreFreezerOverrideSet: function()
	{
		var p = Util.Shell.ExpandEnvironmentString("%PROGRAMFILES%\\Mozilla Firefox\\");
		if(!Util.IO.CheckFileExists(p + this.config))
		{
			return false;
		}
		if(!Util.IO.CheckFileExists(p + this.localSettingsPath))
		{
			return false;
		}
		return true;
	},
	
	SetProductState: function(product, enabled, auto)
	{
		//app.update.auto;true
		//app.update.enabled;true
		var cfg = product.path + this.config;
		var en = enabled ? "true" : "false";
		var av = auto ? "true" : "false";
		var ens = 'lockPref("app.update.enabled",' + en + ');';
		var avs = 'lockPref("app.update.auto",' + av + ');';
		// file must start with //
		var t = "//\n" + ens + "\n" + avs; 
		if(Util.IO.CheckFileExists(cfg))
		{
			t = Util.IO.ReadFile(cfg);
			var re = /^lockPref\([\s'\"]*app.update.enabled[\s'\"]*,[\s'\"]*(true|false)[\s'\"]*\);/im;
			var res = t.match(re);
			if (res != null && res.length > 1)
			{
				t = t.replace(re, ens);
			}
			else
			{
				t = t + '\n' + ens;
			}
			re = /^lockPref\([\s'\"]*app.update.auto[\s'\"]*,[\s'\"]*(true|false)[\s'\"]*\);/im;
			res = t.match(re);
			if (res != null && res.length > 1)
			{
				t = t.replace(re, avs);
			}
			else
			{
				t = t + '\n' + avs;
			}
		}
		Util.IO.WriteFile(cfg, t);
	},
//#endregion
	
//#region Enums
	NOTSET:			 0,
	DISABLED: 		 1,
	NOTIFYONLY: 	 2,
	AUTOMATIC: 		 3,
//#endregion
	
//#region Actions
	Query: function()
	{
		if (!this.CheckProgramInstalled())
		{
			return false;
		}	
	
		this.QueryMozillaProducts();
		
		if (this.updaterEnabled)
		{
			queryResult.push({msg: "<b>" + S("Mozilla.Updater.UpdaterEnabled") + "</b>"});
		}
		else
		{
			queryResult.push({msg: "<b>" + S("Mozilla.Updater.UpdaterDisabled") + "</b>"});
		}
	},
	
	Disable: function()
	{
		this.ChangeMozillaProducts(this.DISABLED);
	},
	
	SetAuto: function()
	{
		this.ChangeMozillaProducts(this.AUTOMATIC);
	},
	
	SetManual: function()
	{
		this.ChangeMozillaProducts(this.NOTIFYONLY);
	},
	
	SetNotSet: function()
	{
		this.ChangeMozillaProducts(this.NOTSET);
	},
	
	Backup: function()
	{
		this.QueryMozillaProducts();
	},
	
	Restore: function()
	{
		this.ChangeMozillaProducts();
	},
//#endregion

	GetScenarioInfo: function()
	{
		Scenario.currentScenario = this;
		
		if (this.IsProgramInstalled)
		{
			if (false == this.IsProgramInstalled())
			{
					return {name: this.name, 
							displayName: this.displayName,
							icon: this.icon,
							status: S("UI.NotInstalled"),
							link: this.link};
			}
		}

		// do backup if first time
		var backupFolder = Util.Scenario.GetDataFolderPath(this.name, "backup");		
		var files = _GetFilesInFolder(backupFolder);
		if (files.length == 0)
		{
			action = "backup";
			Execute(this);
		}
	
		// do query
		this.updaterEnabled = false;
		action = "query";
		var status = Execute(this);
		var dataFileName =  Util.IO.CombinePath(this.dataFolderPath, this.mozillaDataFileName);
		var result = Util.IO.ReadJsonFromFile(dataFileName);
		var updaterEnabled = this.updaterEnabled;
		var state = this.NOTSET;
		if(this.AreFreezerOverrideSet())
		{
			var enabled = false;
			var auto = false;
			
			for(var i = 0; i < result.products.length; i++)
			{
				if (result.products[i].enabled)
				{
					enabled = true;
				}
				if (result.products[i].autoUpdate)
				{
					auto = true;
				}
			}
			if(enabled)
			{
				if(auto)
				{
					state = this.AUTOMATIC;
				}
				else
				{
					state = this.NOTIFYONLY;
				}
			}
			else
			{
				state = this.DISABLED;
			}
		}
		var actionInfo = 
		{
			name: this.name,
			displayName: this.displayName,
			icon: this.icon,
			status: status,
			link: this.link,
		    actions: [
				{
					action: "SetNotSet",
					buttonName: "NotSet",
					active: state == this.NOTSET
				},
				{
					action: "Disable",
					buttonName: "Disabled", 
					active: state == this.DISABLED
				},
				{
					action: "SetManual", 
					buttonName: "NotifyOnly", 
					active: state == this.NOTIFYONLY
				},
				{
					action: "SetAuto",
					buttonName: "Automatic",
					active: state == this.AUTOMATIC
				}
				
			]
		};
	
		return actionInfo;
	}	
}


Util.Scenario.InitializeScenario(Scenario.MozillaUpdater);

if (typeof(g_executeInBatch) == "undefined")
{
	Util.Locale.Load();
	Execute(Scenario.MozillaUpdater);
}

Scenario.MozillaUpdater.OutputDependencies();
