/*
 * KK_OTA.cpp
 *
 *  Created on: Dec 27, 2018
 *      Author: sds
 */


#include "KK_OTA.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include "LSC_Logger.h"

using namespace std;

KK_OTA* KK_OTA::ms_pInstance = NULL;

KK_OTA* KK_OTA::GetInstance() {
	if (ms_pInstance == NULL) {
		ms_pInstance = new KK_OTA();
	}
	return ms_pInstance;
}

KK_OTA::KK_OTA() {
	taskInRunning = false;
}

bool KK_OTA::init(string url){
	if (!taskInRunning) {
		taskInRunning = true;
		target_version_url = url;
		// int ret = EH_ActiveObjectCallManager::GetInstance()->getScheduler().enqueue(new EH_KKEnhanceUpgraderMethodReq(*this,url));
		// if (ret == -1) {
		// 	EH_WARNING("kk enhance upgrader enqueue req failed.\n");
		// 	SendUpgradeReqResp(false);
		// 	taskInRunning = false;
		// }
	} else {
		LOGE("konkeyunzhiyi OTA upgrader task in running.ignore current req.\n");
	}
	pthread_t tid;
	pthread_create(&tid, NULL, run0, this);
	return true;
}
void* KK_OTA::run0(void* opt) {
	KK_OTA* client = (KK_OTA*) opt;
	client->run(opt);
	return NULL ;
}
int  KK_OTA::run(void* opt){
	LOGD("konkeyunzhiyi OTA in...\n");
	string Software_url = "wget "+ target_version_url + "-O  /home/hj/konkeyunzhiyi/konkeyunzhiyi.bin";
	int down_int = system(Software_url.c_str());
	LOGD("下载完成:%d \n",down_int);
	system("chmod 755 /home/hj/konkeyunzhiyi/*");
	system("rm -rf /tmp/konkeyunzhiyi");
	system("tar xzvf /home/hj/konkeyunzhiyi/konkeyunzhiyi.bin -C /tmp/");
	
	pid_t pid;
	if ((pid = fork()) < 0){
		return -1;	/* errno set by fork() */
	}else if (pid == 0) {	/* child */
		int fd =0;
		for (; fd < sysconf(_SC_OPEN_MAX); fd++){
			if (fd!= STDIN_FILENO && fd!= STDOUT_FILENO && fd!= STDERR_FILENO){
				 close(fd);
			}
		}
		LOGD("OTA开始替换适配程序\n");
		system("cd /tmp/konkeyunzhiyi/;sh update.sh");
		system("rm -rf /tmp/konkeyunzhiyi");
		LOGD("OTA适配程序开始重启\n");
		system("killall konkeyunzhiyi");
		exit(0);
	}
	LOGD("适配程序打印konkeyunzhiyi OTA fork child:%d.\n",pid);
	LOGD("适配程序打印konkeyunzhiyi OTA out...\n");
	return 1;
}
