#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>

#include "SHSSDK.h"
#include "SHCSDK.h"

#include "log.h"
#include "protocol.h"

using namespace std;
using namespace SDLog;
using namespace SDSocket;

string strLogPath;
string strLogPrefix = "rccheck";

HSHSDK access_sh(rcacct_t *rcinfo, char *errorMsg)
{
	char *serviceHost = NULL;
	char *authString  = NULL;
	HSHSDK hshsdk = NULL;
	int  errorCode;
	/* System Hosting Server-side SDK : 서비스 서버 얻기 */
	//serviceHost = (char *)sh_get_service_host(userid, userpass, serviceId);
	serviceHost = (char *)sh_get_service_host(rcinfo->m_pszUserName, rcinfo->m_pszPassword, rcinfo->m_pszServiceName);
	if (!serviceHost) {
		errorCode = errno;
		sprintf(errorMsg, "서비스 호스트를 받아오지 못했습니다.");

		if (hshsdk)
			sh_free(hshsdk);

		return NULL;
	}
	fprintf(stderr, "serviceHost : %s\n", serviceHost);

	/* System Hosting Server-side SDK : 인증스트링 얻기 */
	//authString = (char *)sh_get_auth_string(userid, userpass, serviceId, authKey, authFile, time(NULL) + 100000);
	authString = (char *)sh_get_auth_string(rcinfo->m_pszUserName, rcinfo->m_pszPassword, rcinfo->m_pszServiceName, rcinfo->m_pszAuthkey, rcinfo->m_pszCertLocation, time(NULL) + 100000);
	if (!authString) {
		errorCode = errno;
		sprintf(errorMsg, "인증 스트링을 받아오지 못했습니다.");

		if (hshsdk)
			sh_free(hshsdk);
		if (serviceHost)
			free(serviceHost);

		return NULL;
	}
	fprintf(stderr, "authString : %s\n", authString);
	/*
	serviceHost = "222.122.152.33/dav";
	authString = (char *)sh_get_auth_string("kpost", "kpost", "kpost", "geniuspizon", "./kpost48.cert", time(NULL) + 150000);
	*/
	/* System Hosting Client-side SDK : 초기화 */
	hshsdk = sh_init(serviceHost, authString, NULL, NULL);
	if (!hshsdk) {
		errorCode = errno;
		sprintf(errorMsg, "System Hosting Client-side SDK 초기화에 실패하였습니다.");

		if (hshsdk)
			sh_free(hshsdk);
		if (serviceHost)
			free(serviceHost);
		if (authString)
			free(authString);

		return NULL;
	}

#ifndef __TEST__
	if (serviceHost)
		free(serviceHost);
	if (authString)
		free(authString);
#endif

	return hshsdk;
}

int check_rc(char *filename, rcacct_t *rcinfo)
{
	HSHSDK hshsdk = NULL;
	char local_path[128], remote_path[128], local_temp[128];

	int  errorCode;
	char errorMsg[1024];

	LogToFile LFile(strLogPath, strLogPrefix, 0);

	sprintf(local_path, "/tmp/%s", filename);
	sprintf(remote_path, "/INCINERATE/%s", filename);
	sprintf(local_temp, "/tmp/%s.download", filename);

	unlink(local_temp);

	hshsdk = access_sh(rcinfo, errorMsg);
	if (hshsdk) {
		errorCode = sh_upload(hshsdk, local_path, remote_path, SHWRITEPOLICY_OVERWRITE, -1);
#ifdef __DEBUG__
		fprintf(stderr, "error: upload: %d:%s\n", errorCode, sh_get_error_message(hshsdk));
		fprintf(stderr, "debug: step 1 - %s\n", filename);
#endif		
		if (errorCode == 0) {
			LFile << "!check_rc:: RC " << rcinfo->m_pszServiceName << ": upload failed: " << sh_get_error_message(hshsdk) << EL;
			sh_free(hshsdk);
			return -1;
		}
#ifdef __DEBUG__	
		fprintf(stderr, "debug: step 2\n");
#endif
		usleep(500000);
#ifdef __DEBUG__
		fprintf(stderr, "debug: step 3\n");
#endif

		errorCode = sh_download(hshsdk, remote_path, local_temp, SHWRITEPOLICY_OVERWRITE, -1);
#ifdef __DEBUG__
		fprintf(stderr, "debug: step 4\n");
		fprintf(stderr, "error: download: %d:%s\n", errorCode, sh_get_error_message(hshsdk));
#endif
		if (errorCode == 0) {
			LFile << "!check_rc:: RC " << rcinfo->m_pszServiceName << ": download failed: " << sh_get_error_message(hshsdk) << EL;
			sh_free(hshsdk);
			return -1;
		}
#ifdef __DEBUG__
		fprintf(stderr, "debug: step 5\n");
#endif
		sh_delete(hshsdk, remote_path);
#ifdef __DEBUG__
		fprintf(stderr, "debug: step 6\n");
#endif
		sh_free(hshsdk);
	} else {
#ifdef __DEBUG__
		fprintf(stderr, "error: %s\n", errorMsg);
#endif
		LFile << "!check_rc:: RC " << rcinfo->m_pszServiceName << ": access failed: " << errorMsg << ": " << sh_get_error_message(hshsdk) << EL;
		return -1;
	}
	unlink(local_temp);
	fflush(stderr);
	return 0;
}

int check_rc_updown(rcacct_t *rcinfo)
{
	FILE *fp;
	struct timeval tv;
	char tagname[38];
	char tagfull[38];
	int retval = -1;

	//string strLogPath = DEFAULT_LOGFILE_PATH;
	//string strLogPrefix = DEFAULT_LOGFILE_PREFIX;
	LogToFile LFile(strLogPath, strLogPrefix, 0);

	gettimeofday(&tv, NULL);
	sprintf(tagname, "%d%06d", (int)tv.tv_sec, (int)tv.tv_usec);
	sprintf(tagfull, "/tmp/%d%06d", (int)tv.tv_sec, (int)tv.tv_usec);
#ifdef __DEBUG__
	fprintf(stderr, "tagname %s tagfull %s\n", tagname, tagfull);
#endif

	if ((fp = fopen(tagfull, "w"))) {
		//fprintf(fp, "%s", tagname);
		fclose(fp);

		/* start! */
		if (check_rc(tagname, rcinfo)) {
			LFile << "!RC " << rcinfo->m_pszServiceName << " check failed" << EL;
#ifdef __DEBUG__
			fprintf(stderr, "RC %s check failed\n", rcinfo->m_pszServiceName);
#endif
			retval = -1;
		} else {
			//LFile << "!RC " << rcinfo->m_pszServiceName << " check success" << EL;
#ifdef __DEBUG__
			fprintf(stderr, "RC %s check success\n", rcinfo->m_pszServiceName);
#endif
			retval = 0;
		}
		unlink(tagfull);
	}

	return retval;
}

void usage(void)
{
	fprintf(stderr, "rccheck - check rc by ics sdk\n");
	fprintf(stderr, " usage : rccheck <log dir> <volume> <user> <passwd> <authkey> <cert location>\n");
	exit(2);
}

void HandleTimeOut(int signum)
{
	fprintf(stderr, "TIMEOUT!\n");
	exit(1);
	return;
}

int main(int argc, char *argv[])
{
	rcacct_t rcinfo;
	char buf[1024];
	int retval;

#ifdef __DEBUG__
	fprintf(stderr, "argc %d argv %s\n", argc, argv[1]);
#endif

	if (argc != 7) {
		usage();
	}

	strLogPath = argv[1];
	sprintf(buf, "mkdir -p %s\n", argv[1]);
	system(buf);

	memset((char *)&rcinfo, 0, sizeof(rcacct_t));

/*
	typedef struct _RCAcct_e
	{
		char *           m_pszServiceName;
		char *           m_pszUserName;
		char *           m_pszPassword;
		char *           m_pszAuthkey;
		char *           m_pszCertLocation;

		struct _RCAcct_e *next;
	} rcacct_t;
 */

	rcinfo.m_pszServiceName = argv[2];
	rcinfo.m_pszUserName = argv[3];
	rcinfo.m_pszPassword = argv[4];
	rcinfo.m_pszAuthkey = argv[5];
	rcinfo.m_pszCertLocation = argv[6];

	::signal(SIGALRM, HandleTimeOut);
	::alarm(60);
	if ((retval = check_rc_updown(&rcinfo)) != 0) {
#ifdef __DEBUG__
		fprintf(stderr, "RC %s check failed\n", rcinfo.m_pszServiceName);
#endif		
		//sleep(10);
		usleep(1);
		exit(1);
	} else {
#ifdef __DEBUG__
		fprintf(stderr, "RC %s check success\n", rcinfo.m_pszServiceName);
#endif		
		//sleep(1);
		usleep(1);
		exit(0);
	}
	::alarm(0);
	exit(1);
}
