/*
 * <insert one-line description of what the program does>
 * Copyright (c) <2008-2009>, Intel Corporation.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms and conditions of the GNU Lesser General Public License,
 * version 2.1, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
 * more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 
 * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
 *
 */
#include "GUI/resmgmt.h"
#include <stdio.h>
#include "InfoMgmt/InfoMgmt.h"
#include "GUI/error.h"
#include "GUI/macro.h"


RESOURCE_MANAGER g_resManager;

RESOURCE_ITEM_MAP g_resMapTable[] = {
{"T_strTCAgentTitle",&g_resManager.T_strTCAgentTitle},

{"T_strPageServer",&g_resManager.T_strPageServer},

{"T_strPageExpiration",&g_resManager.T_strPageExpiration},

{"T_strPageDownload",&g_resManager.T_strPageDownload},

{"T_strBtnOK",&g_resManager.T_strBtnOK},

{"T_strBtnCancel",&g_resManager.T_strBtnCancel},

{"T_strBtnApply",&g_resManager.T_strBtnApply},

{"T_strlabServer",&g_resManager.T_strlabServer},

{"T_strlabProxy",&g_resManager.T_strlabProxy},

{"T_strlabProxyName",&g_resManager.T_strlabProxyName},

{"T_strlabProxyPwd",&g_resManager.T_strlabProxyPwd},

{"T_strgroupServer",&g_resManager.T_strgroupServer},

{"T_strgroupProxy",&g_resManager.T_strgroupProxy},

{"T_strlabDays",&g_resManager.T_strlabDays},

{"T_strlabTimes",&g_resManager.T_strlabTimes},

{"T_strgroupPrompt",&g_resManager.T_strgroupPrompt},

{"T_strlabDeviceID",&g_resManager.T_strlabDeviceID},

{"T_strlabHardwareID",&g_resManager.T_strlabHardwareID},

{"T_strlabExpiryDate",&g_resManager.T_strlabExpiryDate},

{"T_strlabBootAble",&g_resManager.T_strlabBootAble},

{"T_strlabNote",&g_resManager.T_strlabNote},

{"T_strlabIP",&g_resManager.T_strlabIP},

{"T_strlabGatewayIP",&g_resManager.T_strlabGatewayIP},

{"T_strlabProxyIP",&g_resManager.T_strlabProxyIP},

{"T_strlabDNSIP",&g_resManager.T_strlabDNSIP},

{"T_strlabWINSIP",&g_resManager.T_strlabWINSIP},

{"T_strlabDownload",&g_resManager.T_strlabDownload},

{"T_strbtnDownload",&g_resManager.T_strbtnDownload},

{"T_strlabPermanent",&g_resManager.T_strlabPermanent},

{"T_strlabUnlimited",&g_resManager.T_strlabUnlimited},

{"T_strgroupDevice",&g_resManager.T_strgroupDevice},

{"T_strgroupExpiry",&g_resManager.T_strgroupExpiry},

{"T_strgroupNetWork",&g_resManager.T_strgroupNetWork},

{"T_strgroupDownload",&g_resManager.T_strgroupDownload},

{"T_strNotifyNormal",&g_resManager.T_strNotifyNormal},

{"T_strNotifyWarning",&g_resManager.T_strNotifyWarning},

{"T_strNotifyUrgency",&g_resManager.T_strNotifyUrgency},

{"T_strNotifyDownloading",&g_resManager.T_strNotifyDownloading},

{"T_strtipServerAddress",&g_resManager.T_strtipServerAddress},

{"T_strtipProxyAddress",&g_resManager.T_strtipProxyAddress},

{"T_strtipProxyName",&g_resManager.T_strtipProxyName},

{"T_strtipProxyPwd",&g_resManager.T_strtipProxyPwd},

{"T_strtipDays",&g_resManager.T_strtipDays},

{"T_strtipTwice",&g_resManager.T_strtipTwice},

{"T_strcheckBoxUseProxy", &g_resManager.T_strcheckBoxUseProxy}, //add by xu jun

{"M_strMsgTitleInfomation",&g_resManager.M_strMsgTitleInfomation},

{"M_strMsgTitlePrompt",&g_resManager.M_strMsgTitlePrompt},

{"M_strStartFail",&g_resManager.M_strStartFail},

{"M_strDownloadedOnce",&g_resManager.M_strDownloadedOnce},

{"M_strDownloadSuccess",&g_resManager.M_strDownloadSuccess},

{"M_strDownloadFail",&g_resManager.M_strDownloadFail},

{"M_strRefuseService",&g_resManager.M_strRefuseService},

{"M_strErrorConnect",&g_resManager.M_strErrorConnect},

{"M_strUnable",&g_resManager.M_strUnable},

{"M_strData",&g_resManager.M_strData},

{"M_strException",&g_resManager.M_strException},

{"M_strUnknow",&g_resManager.M_strUnknow},

{"M_strInvalid",&g_resManager.M_strInvalid},

{"M_strLocal",&g_resManager.M_strLocal},

{"M_strIllegal",&g_resManager.M_strIllegal},

{"M_strDayError",&g_resManager.M_strDayError},

{"M_strTimesError",&g_resManager.M_strTimesError},

{"M_strProxyNameError",&g_resManager.M_strProxyNameError},

{"M_strProxyPwdError",&g_resManager.M_strProxyPwdError},

{"M_strAutoDownloading",&g_resManager.M_strAutoDownloading},

{"M_strCantChange",&g_resManager.M_strCantChange},

{"M_strNeedProxyAddress",&g_resManager.M_strNeedProxyAddress},

{"M_strNeedProxyName",&g_resManager.M_strNeedProxyName},

{"M_strNeedAddressAndName",&g_resManager.M_strNeedAddressAndName},

{"M_strSaveCertError",&g_resManager.M_strSaveCertError},

{"M_strErrorCode",&g_resManager.M_strErrorCode},

{"W_strlabExpireIn",&g_resManager.W_strlabExpireIn},

{"W_strlabDays",&g_resManager.W_strlabDays},

{"W_strlabTimes",&g_resManager.W_strlabTimes},

{"W_strlabWarning",&g_resManager.W_strlabWarning},

{"W_strgroupPrompt",&g_resManager.W_strgroupPrompt},

{"W_strlabWarningInfo",&g_resManager.W_strlabWarningInfo},

{"W_strTitle",&g_resManager.W_strTitle},

{"P_strlabTitle",&g_resManager.P_strlabTitle},

{"P_strlabDownloading",&g_resManager.P_strlabDownloading},

{"R_strlabTitle",&g_resManager.R_strlabTitle},

{"R_strgroupPrompt",&g_resManager.R_strgroupPrompt},

{"R_labInfo",&g_resManager.R_labInfo},

{"R_btnRebootNow",&g_resManager.R_btnRebootNow},

{"R_labRemain",&g_resManager.R_labRemain},

{"M_strTimeout",&g_resManager.M_strTimeout},

{"M_strHWIDInvalid",&g_resManager.M_strHWIDInvalid},

{"M_strBootTickInvalid",&g_resManager.M_strBootTickInvalid},

{"M_strDeviceStolen",&g_resManager.M_strDeviceStolen},

{"M_strSystem",&g_resManager.M_strSystem},

{"M_strTPM",&g_resManager.M_strTPM },

{"M_strTwoInstance", &g_resManager.M_strTwoInstance},

{"M_strError", &g_resManager.M_strError},

//liu.j add
{"G_strTooltipText", &g_resManager.G_strTooltipText},

{"G_strDisableNoConnection", &g_resManager.G_strDisableNoConnection},

{"G_strNoConnection", &g_resManager.G_strNoConnection},

{"G_strNotApproved", &g_resManager.G_strNotApproved},

{"G_strPermanentCertificate", &g_resManager.G_strPermanentCertificate},

{"G_strStatusNotApproved", &g_resManager.G_strStatusNotApproved},

{"G_strStatusWarning", &g_resManager.G_strStatusWarning},

{"G_strStatusNormal", &g_resManager.G_strStatusNormal},

{"G_strBalloonText", &g_resManager.G_strBalloonText},

{"G_strNoConnection2", &g_resManager.G_strNoConnection2},

{"G_strBubbleHeader", &g_resManager.G_strBubbleHeader},

{"G_strMenuItemAbout", &g_resManager.G_strMenuItemAbout},

{"G_strMenuItemLogin", &g_resManager.G_strMenuItemLogin},

{"G_strMenuItemSettings", &g_resManager.G_strMenuItemSettings},

{"G_strMenuItemHelp", &g_resManager.G_strMenuItemHelp},
//liu.j add end

{"G_strDownloadCASuceed", &g_resManager.G_strDownloadCASuceed},


{"A_strTitle", &g_resManager.A_strTitle},

{"A_strLicense", &g_resManager.A_strLicense},

};
static char *str_copy(char *dest, char *src)
{
	
	if(NULL == dest || NULL == src)
	{
		return NULL;
	}
	
	char *tmp = src;
	*dest = '\0';
	while(*tmp)
	{
		if('\\' != *tmp)
		{
			*dest++ = *tmp++;
		}else
		{
			tmp++;
			if('n' == *tmp)
			{
				*dest++ = '\n';				
			}else
			{
				//by now we suppose it's allright, but...
				//be carefull with the localization text!
				//now we only parse "\n", no support for  "\r", "\\", etc.  
			}
			tmp++;
		}		
	}
	*dest = '\0';
	return dest;
}
int ReadResources()
{
	FILE* file;
	char tmp[RESOURCE_MAX_LEN];
	char name[RESOURCE_NAME_LEN];
	char value[RESOURCE_MAX_LEN];
	char* tmp2 = NULL;
	int pos=0;
	int len = 0;
	int i=0;
	char pculture[TEMP_MAX_LEN];
	char resfilename[FILEPATH_MAX_LEN];


	memset(&g_resManager,0,sizeof(g_resManager));
	strcpy(g_resManager.T_strlabUnlimited ,"Unlimited");
	strcpy(g_resManager.T_strlabPermanent ,"Permanent");
	
	strcpy(g_resManager.M_strMsgTitleInfomation ,"Information");

	strcpy(g_resManager.M_strStartFail   ,"Program launch failed!");
	strcpy(g_resManager.M_strMsgTitleInfomation ,"Prompt");
	strcpy(g_resManager.M_strDownloadedOnce  ,"Sorry. You have to re-log in or reboot your system for your next download.");
	strcpy(g_resManager.M_strDownloadSuccess  ,"Download succeeded!");
	strcpy(g_resManager.M_strDownloadFail  ,"Download failed!");
	strcpy(g_resManager.M_strRefuseService  ," Service denied!");
	strcpy(g_resManager.M_strErrorConnect  ,"Error while connecting to server!");
	strcpy(g_resManager.M_strUnable  ,"Unable to authenticate server!");
	strcpy(g_resManager.M_strData ,"Data from server is corrupted!");
	strcpy(g_resManager.M_strException  ,"Exception occurred at server!");
	strcpy(g_resManager.M_strUnknow  ,"Unknown exception occurred!");
	strcpy(g_resManager.M_strInvalid  ,"Invalid Hardware ID!");
	strcpy(g_resManager.M_strLocal ,"Local Boot Tick is inconsistent with server Boot Tick!");
	strcpy(g_resManager.M_strIllegal  ,"Illegal possession of this device!");
	strcpy(g_resManager.M_strDayError  ,"Input a digit between 1-30.");
	strcpy(g_resManager.M_strTimesError  ,"Input a digit between 1-100.");
	strcpy(g_resManager.M_strProxyNameError  ,"Proxy user name error!");
	strcpy(g_resManager.M_strProxyPwdError  ,"Proxy password error!");
	strcpy(g_resManager.M_strAutoDownloading  ,"Currently automatically downloading!");
	strcpy(g_resManager.M_strCantChange  ,"You can't change the configuration!");
	strcpy(g_resManager.M_strNeedProxyAddress  ," Please input proxy address!");
	strcpy(g_resManager.M_strNeedProxyName  ,"Please input proxy user name!");
	strcpy(g_resManager.M_strNeedAddressAndName  ,"Please input proxy address and proxy user name!");
	strcpy(g_resManager.M_strSaveCertError  ,"Save cert error!");
	strcpy(g_resManager.M_strErrorCode  ,"Error Code");
	strcpy(g_resManager.M_strTimeout  ,"Connection Timeout.");
	strcpy(g_resManager.M_strHWIDInvalid  ,"Hardware ID invalid.");
	strcpy(g_resManager.M_strBootTickInvalid  ,"Boot Tick invalid.");
	strcpy(g_resManager.M_strDeviceStolen  ,"Device is stolen.");
	strcpy(g_resManager.M_strSystem  ," System Error.");
	strcpy(g_resManager.M_strTPM  ,"TPM Error.");
        strcpy(g_resManager.T_strNotifyNormal, "Normal");
        strcpy(g_resManager.T_strNotifyWarning, "Warning");
        strcpy(g_resManager.T_strNotifyUrgency, "Urgency");
        strcpy(g_resManager.T_strNotifyDownloading, "Downloading");

	strcpy(g_resManager.T_strcheckBoxUseProxy, "Use Proxy Server"); //add by xu jun

	strcpy(g_resManager.M_strTwoInstance, "TheftDeterrent may be already running! If not, please "
			"remove /tmp/theftdeterrent/.tdlock file.");

	strcpy(g_resManager.G_strDownloadCASuceed  ,"Root CA verify error, the root CA Package was downloaded again!");

	strcpy(g_resManager.M_strError, "Error");
	//liu.j add 
	strcpy(g_resManager.G_strTooltipText, "Theft Deterrent %s\nHardware ID: %s\n"
			"Expiration Date: %d-%d-%d\nRemaining Boots: %d\nBoot Tick: %d"); //changed by xu jun
	strcpy(g_resManager.G_strDisableNoConnection, "Theft deterrent is not "
			"activated and server can not be connected.");
	strcpy(g_resManager.G_strNoConnection, "Theft deterrent server can not be connected.");
	strcpy(g_resManager.G_strNotApproved, "Theft deterrent account has not been approved.");
	strcpy(g_resManager.G_strPermanentCertificate, "Theft deterrent(Permanent)"
			"certificate.\n\nHardware ID: %s");
	strcpy(g_resManager.G_strBalloonText, "Certificate has %s days to expire.\nCertificate has %d system "
			"boot(s) to expire.\n\nTo avoid disruption of computer usage, please make sure your computer "
			"is properly connected to the network to be able to download certificates from the "
			"theft deterrent server.");
	strcpy(g_resManager.G_strStatusNotApproved, "(Not activated)");
	strcpy(g_resManager.G_strStatusWarning, "(Warning)");
	strcpy(g_resManager.G_strStatusNormal, "(Normal)");
	strcpy(g_resManager.G_strNoConnection2, "Can not connect with server.");
	strcpy(g_resManager.G_strBubbleHeader, "Theft Deterrent Agent");
	strcpy(g_resManager.G_strMenuItemAbout, "About...");
	strcpy(g_resManager.G_strMenuItemLogin, "Log onto server");
	strcpy(g_resManager.G_strMenuItemSettings, "Settings");
	strcpy(g_resManager.G_strMenuItemHelp, "Help");
	//liu.j add end

	
	OtherInfo_Culture(pculture, "GET");
	trim(pculture);
        getrespath(THEFTCONTROL_CONFIG,resfilename);
	if (strlen(resfilename) > (FILEPATH_MAX_LEN - strlen("/mystrings.en.txt")))
		return GUI_ERR_FILE_NOT_OPEN;
//normally, resfilename is /etc/theftcontrol/mystrings.%s.txt
	sprintf(resfilename, "%s/mystrings.%s.txt", resfilename,pculture);
	WritestrLog(MODULE_GUI,resfilename);


	//g_print("louis: %s\n", resfilename);
	if ((file = fopen(resfilename, "r"))== NULL)	
	{		
		return GUI_ERR_FILE_NOT_OPEN;
	}
	//UTF-8 format file, skip the file head, FF FE
	fseek(file,3,SEEK_SET);
	while(!feof(file))
	{	
		fgets(tmp, RESOURCE_MAX_LEN-1, file);
		tmp[strlen(tmp)] = '\0';
//	       printf("0x%x",tmp + strlen(tmp) - 1);	
	/*	if (strlen(tmp)>=1)
		if (tmp[strlen(tmp)-1] == 0x0d || tmp[strlen(tmp)-1] == 0x0a)
		        tmp[strlen(tmp)-1] = '\0';
		if (strlen(tmp)>=2)
		if (tmp[strlen(tmp)-2]==0x0d || tmp[strlen(tmp)-2] == 0x0a)
			tmp[strlen(tmp)-2] = '\0';
*/
		memset(name,0,RESOURCE_NAME_LEN);
		memset(value,0,RESOURCE_MAX_LEN);	
		tmp2 =  strchr(tmp,RESOURCE_SPLIT);
		
		if (tmp2 == NULL)
		//	return GUI_ERR_RESOURCE_FORMAT;
			continue;
		pos = tmp2 - tmp;
	
		len = strlen(tmp);
		if (pos > len-1)
			pos = len - 1;
		strncpy(name,tmp,pos-1);//format: name = value
		name[pos] = '\0';
		
		strncpy(value, tmp+pos+2, len-1 - (pos+2) ); 
		value[len-1 - (pos+2)] = '\0';
	//	printf("%s = %s \n",name, value);
			
	/*	if ((strcmp(name,"T_strTCAgentTitle") == 0||strcmp(name,"M_strError")==0) && strcmp(pculture, "en")!= 0 )
		if (value != NULL&&strlen(value)>=1)
			value[strlen(value) - 1] = '\0';
	*/
		for (i=0;i<sizeof(g_resMapTable)/sizeof(RESOURCE_ITEM_MAP);i++)
		{
			if (strcmp(name,g_resMapTable[i].Name) == 0)
#if 0//liu.j
				strcpy((char *)g_resMapTable[i].Value, value);
#else
			str_copy((char *)g_resMapTable[i].Value, value);
#endif
		}	

	}
	fclose(file);

	/*	for (i=0;i<sizeof(g_resMapTable)/sizeof(RESOURCE_ITEM_MAP);i++)
		{
			printf("%s = %s \n",g_resMapTable[i].Name,
				(char *)(((char *)g_resMapTable[i].Value)));
		}	*/
}

int getrespath(int resid,char* resvalue )
{
	FILE* file=NULL;
	char line[FILEPATH_MAX_LEN];
	char* value=NULL,*tmp=NULL;
		         
	memset(line,0,FILEPATH_MAX_LEN);
	if ((file = fopen(TC_INST_ROOT_FILE, "r"))== NULL)
		goto RESOURCE_DEFAULT_VALUE;

	fgets(line, FILEPATH_MAX_LEN-1, file);
	line[strlen(line)-1] = '\0'; //remove the end-of-line character
	fclose(file);
	tmp =  strstr(line,TC_INST_ROOT_KEY);

	if (tmp == NULL || (tmp - line != 0))
		goto RESOURCE_DEFAULT_VALUE;
	value = tmp + strlen(TC_INST_ROOT_KEY);

	value = trim(value);
	if (strcmp(value,"")==0)
		goto RESOURCE_DEFAULT_VALUE;
	int length = (strlen(value)>(FILEPATH_MAX_LEN-strlen("/pixmaps/theftdeterrent"))?(FILEPATH_MAX_LEN-strlen("/pixmaps/theftdeterrent")):strlen(value));
	strncpy(resvalue, value,length);
	resvalue[length] = '\0';
	if (resid == THEFTCONTROL_BINARY)
	        strncat(resvalue,"/bin",strlen("/bin"));
	else if (resid == THEFTCONTROL_CONFIG)
	        strncat(resvalue, "/etc/theftdeterrent",strlen("/etc/theftdeterrent"));
	else if (resid == THEFTCONTROL_PIXMAPS)
	        strncat(resvalue, "/pixmaps/theftdeterrent",strlen("/pixmaps/theftdeterrent"));
	else if (resid == THEFTCONTROL_LOG)
		strncat(resvalue, "/log",strlen("/log"));
	return resvalue;
RESOURCE_DEFAULT_VALUE:
	if (resid == THEFTCONTROL_BINARY)
	{	strncpy(resvalue,"/usr/bin",strlen("/usr/bin"));
		resvalue[strlen("/usr/bin")]='\0';
	}
	else if (resid == THEFTCONTROL_CONFIG)
	{	strncpy(resvalue, "/etc/theftdeterrent",strlen("/etc/theftdeterrent"));
		resvalue[strlen("/etc/theftdeterrent")]='\0';
	}
	else if (resid == THEFTCONTROL_PIXMAPS)
	{	strncpy(resvalue, "/usr/local/pixmaps/theftdeterrent",strlen("/usr/local/pixmaps/theftdeterrent"));
		resvalue[strlen("/usr/local/pixmaps/theftdeterrent")]= '\0';
	}

	else if (resid == THEFTCONTROL_LOG)
	{	strncpy(resvalue,"/tmp",strlen("/tmp"));
		resvalue[strlen("/tmp")]='\0';
	}
	return resvalue;
}
