--[[

useragent changer

for menu.cfg
	
	luamacro(useragent, K-Meleon (Default))
	luamacro(useragent1, Internet Explorer 6 (XP))
	luamacro(useragent2, Netscape 4.8 (XP))
	luamacro(useragent3, Opera 7.54 (XP))
	luamacro(customagent, Custom...)
	
	or
	
	luamacro(change_useragent(0), K-Meleon (Default))
	luamacro(change_useragent(1), Internet Explorer 6 (XP))
	luamacro(change_useragent(2), Netscape 4.8 (XP))
	luamacro(change_useragent(3), Opera 7.54 (XP))
	luamacro(customagent, Custom...)
	
	or
	
	luamacro(change_useragent, Select UserAgent)
	luamacro(customagent, Custom UserAgent)
]]

require "hook"

local max_ua = 0

-- recognize useragent list automatically
do
	local i = 0
	local name
	
	name = km.getpref(TYPE_STRING, "kmeleon.privacy.useragent" .. tostring(i) .. ".name")
	while name and name ~= "" do
		max_ua = i
		i = i + 1
		name = km.getpref(TYPE_STRING, "kmeleon.privacy.useragent" .. tostring(i) .. ".name")
	end
end

local function sync(n)
	local i
	
	if not n then
		local uas, ua
		ua = km.getpref(TYPE_STRING, "general.useragent.override")
		if not ua or ua == "" then
			n = 0
		else
			for i = 1, max_ua, 1 do
				uas = km.getpref(TYPE_STRING, "kmeleon.privacy.useragent" .. tostring(i) .. ".string")
				if ua == uas then
					n = i
					break
				end
			end
		end
	end
	setcheck("luamacro(useragent)", n == 0)
	setcheck("luamacro(change_useragent(0))", n == 0)
	for i = 1, max_ua, 1 do
		setcheck("luamacro(useragent" .. tostring(i) .. ")", i == n)
		setcheck("luamacro(change_useragent(" .. tostring(i) .. "))", i == n)
	end
end

function customagent()
	local uas = getpref(TYPE_STRING, "general.useragent.override")
	uas = prompt("Enter the User Agent string to identify K-Meleon as:",
		"Custom User Agent", uas);
	if uas then
		setpref(TYPE_STRING,"general.useragent.override", uas)
	end
end

function change_useragent(n)
	local i
	if not n then
		local t = {}
		for i = 0, max_ua, 1 do
			local uan = km.getpref(TYPE_STRING,
				"kmeleon.privacy.useragent" .. tostring(i) .. ".name")
			t[i + 1] = uan
		end
		n = km.select("select useragent", "K-Meleon", unpack(t))
		if not n then
			return
		end
		n = n - 1
	end
	if n > max_ua then
		return
	elseif n == 0 then
		km.delpref("general.useragent.override")
	else
		local uas = km.getpref(TYPE_STRING,
			"kmeleon.privacy.useragent" .. tostring(n) .. ".string")
		if not uas or uas == "" then
			return
		end
		setpref(TYPE_STRING, "general.useragent.override", uas)
	end
	sync(n)
end

function useragent() change_useragent(0); end
function useragent1() change_useragent(1); end
function useragent2() change_useragent(2); end
function useragent3() change_useragent(3); end
function useragent4() change_useragent(4); end

function useragent_sync()
	sync()
end

hook.add(StartupHook, sync)
