#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <string.h>

#include "curl.h"
#include "./jsonrpc/rpccJSON.h"

static int s_ota_server_init = 0;

size_t kk_write_func(void *ptr, size_t size, size_t nmemb, FILE *stream)
{
    return fwrite(ptr, size, nmemb, stream);
} 
 
int kk_progress_func(char *progress_data,
                     double t, /* dltotal */
                     double d, /* dlnow */
                     double ultotal,
                     double ulnow)
{

    printf("%s %g / %g (%g %%)\n", progress_data, d, t, d*100.0/t);
    return 0;
}
 
int kk_http_download(char* url, char* filename)
{
    CURL *curl;
    CURLcode res;
    FILE *outfile;
    char *progress_data = "* ";

    if (url == NULL || filename == NULL){
        printf("params error url or filename \n");
        return -1;
    }

    curl = curl_easy_init();
    if(curl)
    {
        outfile = fopen(filename, "wb");//fopen("test.jpg", "wb");

        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, outfile);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, kk_write_func);
        curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
        curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, kk_progress_func);
        curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, progress_data);

        res = curl_easy_perform(curl);

        fclose(outfile);
        /* always cleanup */
        curl_easy_cleanup(curl);
    }
    return 0;
}


static const char oatStorageDirectory[] = "ota-files";

int kk_ota_process(cJSON* root){
    cJSON *params;
    cJSON *id;
    cJSON *mac;
    cJSON *info;
    cJSON *msgType;
    cJSON *payload;
    cJSON *url;
    cJSON *md5;
    cJSON *size;
    int ret = 0;
    struct stat st;
    int iFileSize;
    char fileName[100] = {0};
    

	info = rpc_cJSON_GetObjectItem(root, "info"); 
	if(info != NULL){
		
		msgType = rpc_cJSON_GetObjectItem(info, "msgType");
		mac = rpc_cJSON_GetObjectItem(info, "deviceCode");		
	}
	payload	= rpc_cJSON_GetObjectItem(root, "payload"); 
	if(payload != NULL){

		params = rpc_cJSON_GetObjectItem(payload, "data");
		//id = rpc_cJSON_GetObjectItem(payload, "msgId");
		url = rpc_cJSON_GetObjectItem(params, "url");
		md5 = rpc_cJSON_GetObjectItem(params, "md5");
		size = rpc_cJSON_GetObjectItem(params, "size");
        printf("===============kk_ota_process ===========[%s][%s][%s]\n", url->valuestring,mac->valuestring,size->valuestring);
        sprintf(fileName, "%s/%s.%s", oatStorageDirectory, mac->valuestring, "ota");
		kk_http_download(url->valuestring, fileName);

        if(stat(mac->valuestring, &st))
                printf("读取出错！\n");

        iFileSize = st.st_size;
        if (iFileSize != atoi(size->valuestring)){
            printf("check file size failed [%d][%s] \n", iFileSize, size->valuestring);
            return -1;
        }
        char md5File[21] = {0};
        char cmd[100] = {0};
        char md5str[34] = {0};
        FILE *fp;
        sprintf(md5File, "%s.md5", mac->valuestring);
        sprintf(cmd, "md5sum %s|cut -d\" \" -f1 > %s", fileName, md5File);

        system(cmd);
        
		//snprintf(filepath, sizeof(filepath), "./%s", "alinkconf");
        fp = fopen(md5File, "r");
        if (!fp) {
            printf("open file failed \n");
            return -1;
        }
        
        int readlen = fread(md5str, 1, 32, fp);
        printf("md5sum readlen=%d, md5str=%s,md5->valuestring=%s \n", readlen, md5str,md5->valuestring);
        
        if (readlen > 0 && strcmp(md5str, md5->valuestring) == 0){
            printf("check md5sum succees\n");
            ret = 0;
        }else{
            printf("check md5sum failed \n");
            ret = -1;
        }

        fclose(fp);

        remove(md5File);

        kk_ota_notify(fileName);
        
        return ret;
	} 
    return -1;
}























