#include <stdio.h>      /*標準輸入輸出定義*/
#include <stdlib.h>     /*標準函數庫定義*/
#include <string.h>
#include <stdint.h>

#include <sys/types.h>
#include <dirent.h>

#include "../Config.h"
#include "../Log/log.h"
#include "../Define/define.h"
#include "../ShareMemory/shmMem.h"

//------------------------------------------------------------------------------
void zipLogFiles(void)
{
    const char *logPath = "/Storage/SystemLog";

    // 獲取目錄
    DIR *pDir = opendir(logPath);
    if (pDir != NULL) {
        struct timeb csuTime;
        struct tm *tmCSU;

        ftime(&csuTime);
        tmCSU = localtime(&csuTime.time);
//      log_info("Time : %04d-%02d-%02d %02d:%02d:%02d \n", tmCSU->tm_year + 1900,
//          tmCSU->tm_mon + 1, tmCSU->tm_mday, tmCSU->tm_hour, tmCSU->tm_min,
//          tmCSU->tm_sec);

        // Read items inside the folder
        struct dirent *pEntry = NULL;
        while ((pEntry = readdir(pDir)) != NULL) {
            if (strcmp(pEntry->d_name, ".") != 0 &&
                    strcmp(pEntry->d_name, "..") != 0 &&
                    strncmp(pEntry->d_name, "[", 1) == 0 &&
                    strstr(pEntry->d_name, "tar") < 0) {
                char yearC[5];
                unsigned short year = 0;
                char monthC[3];
                unsigned short month = 0;

                yearC[4] = '\0';
                strncpy(yearC, pEntry->d_name + 1, 4);
                monthC[2] = '\0';
                strncpy(monthC, pEntry->d_name + 6, 2);

                year = atoi(yearC);
                month = atoi(monthC);

                if (year != 0) {
                    if (year < tmCSU->tm_year + 1900 ||
                            (year >= tmCSU->tm_year + 1900 && month < tmCSU->tm_mon + 1)) {
                        log_info("tar file name : %s \n", pEntry->d_name);
                        char file[256];

                        memset(file, 0x00, sizeof(file));
                        strcat(file, "tar zcvf ");
                        strcat(file, logPath);
                        strncat(file, "/", 1);
                        strcat(file, pEntry->d_name);
                        strcat(file, ".tar");
                        strncat(file, " ", 1);
                        strcat(file, logPath);
                        strncat(file, "/", 1);
                        strcat(file, pEntry->d_name);
                        log_info("zip = %s \n", file);
                        system(file);
                    }
                }
            }
        }
    }

    // Close folder
    closedir(pDir);
}