
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <linux/types.h>
#include <unistd.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <netdb.h>        /* getaddrinfo(3) et al.                       */
#include <netinet/in.h>   /* sockaddr_in & sockaddr_in6 definition.      */
#include  <net/if.h>
#include <sys/prctl.h>
#include "driver.h"
#include "hal_interface_api.h"
#include "main.h"

int main()
{
	int i;
	uint8_t *buf;//[64*1024+1] = {0};	//4KB, one sector
	uint8_t *chkBuf;//[4*1024] = {0};
	FILE *fp;
	size_t len, totalSize = 1, writeSize = 0;
	FILE *fprogress;
	uint8_t progressStr[10] = {0};
	uint8_t rate = 0;

	buf = malloc(64*1024);
	chkBuf = malloc(64*1024);

	fp = fopen("/var/www/goahead/tmp/tmp.uImage", "rb");
	if(NULL == fp)
	{
		printf("Open image file fail!\n");
		return -1;
	}

	//get file total size
	fseek(fp, 0, SEEK_END);
	totalSize = ftell(fp);
	fseek(fp, 0, SEEK_SET);
	printf("Image size: %d\n", totalSize);

//用来保存更新的进度
		fprogress = fopen("/var/www/goahead/tmp/UpdateProgress.log", "w");
		if(NULL == fp)
		{
			printf("Create UpdateProgress.log file fail!\n");
			//return -1;
		}
		sprintf(progressStr, "%d", rate);
		fputs(progressStr, fprogress);	
		fclose(fprogress);	

	printf("Chip erase ...\n");
	sf_chip_erase(5);
	printf("Chip erase finished!\n");

	do{
		len = fread(buf, 1, 64*1024, fp);
		if(len <= 0)
		{
			close(fp);
			printf("Read file fail!\n");
			break;
		}

		//update Flash
		//sf_sector_erase(5, writeSize);
		sf_write(5, writeSize, buf, len);
		
		// sf_read(5, writeSize, chkBuf, len);
		// if(memcmp(buf, chkBuf, len) != 0)
		// {
		// 	printf("---> chk fail, offset %#x, len %d\n", writeSize, len);
		// 	break;
		// }
	
		writeSize += len;
		rate = (writeSize*100)/totalSize;
		printf("writeSize: %d, len: %d, rate: %d\n", writeSize, len, rate);			

		//用来保存更新的进度
		fprogress = fopen("/var/www/goahead/tmp/UpdateProgress.log", "w");
		if(NULL == fp)
		{
			printf("Create UpdateProgress.log file fail!\n");
			//return -1;
		}
		sprintf(progressStr, "%d", rate);
		fputs(progressStr, fprogress);	
		fclose(fprogress);	
	}while(writeSize < totalSize);
	
	close(fp);

	printf("Update Flash finish.\n");

	//Verify
	printf("Verigy successful.\n");
	//用来保存校验结果
	fprogress = fopen("/var/www/goahead/tmp/Verify.log", "w");
	if(NULL == fp)
	{
		printf("Create UpdateProgress.log file fail!\n");
	}
	sprintf(progressStr, "Verify OK");
	fputs(progressStr, fprogress);
	fclose(fprogress);

	fclose(fp);

	free(buf);
	free(chkBuf);
	return 0;
}
