
#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[4*1024] = {0};	//4KB, one sector
	FILE *fp;
	size_t len, totalSize = 1, writeSize = 0;
	FILE *fprogress;
	uint8_t progressStr[10] = {0};
	uint8_t rate = 0;

	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);

	do{
		len = fread(buf, 1, 4*1024, fp);
		if(len <= 0)
		{
			close(fp);
			printf("Read file fail!\n");
			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);

		//TODO: update Flash
		usleep(10000);
		
	}while(writeSize < totalSize);

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

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

	fclose(fp);
	return 0;
}
