[Feature][T108][task-view-1683] update log manage program

Only Configure: No
Affected branch: GSW_V1453
Affected module: log
Self-test: yes
Doc Update: no

Change-Id: I582bc596bfae016ef9a0df50f283ddbb9304b191
diff --git a/marvell/lte-telephony/configuration/mrvl_tel_diag.cfg b/marvell/lte-telephony/configuration/mrvl_tel_diag.cfg
index 4bb2ee0..6ea751f 100644
--- a/marvell/lte-telephony/configuration/mrvl_tel_diag.cfg
+++ b/marvell/lte-telephony/configuration/mrvl_tel_diag.cfg
@@ -19,13 +19,13 @@
 
 [SDSettings]
 #Maximum Log File Number
-max_log_num=15
+max_log_num=10
 #Current Folder Number
 folder_num=0
 #Auto Increment Folder Number on Startup
-auto_inc=1
+auto_inc=0
 #Log File Size in MBytes
-log_size=10
+log_size=60
 #SD mode mount point
 mount_path=/mnt/mmcblk0
 #SD mode directory
diff --git a/mbtk/rootfs/etc/init.d/mbtk_boot_server_ready b/mbtk/rootfs/etc/init.d/mbtk_boot_server_ready
index 26ab10a..d21024c 100755
--- a/mbtk/rootfs/etc/init.d/mbtk_boot_server_ready
+++ b/mbtk/rootfs/etc/init.d/mbtk_boot_server_ready
@@ -20,10 +20,10 @@
 
 	#mbtk_start /bin/mbtk_info_test
 	mbtk_start /bin/mbtk_logd
-        mbtk_start /bin/gsw_log_check
     # i2s ×ó¶ÔÆë´«ÊäģʽÉèÖÃÖ¸Áî
 	#ubus call audio_if config_pcmexpert "{ 'frame_format': 1, 'invert_frame' : 0, 'frame_polarity' : 1, 'bitclk_polarity' : 0, 'fsyc_shift' : 1}"
-	echo "--mbtk server ready boot end--" > /dev/kmsg
+        /etc/mbtk/gsw_log_manage.sh
+        echo "--mbtk server ready boot end--" > /dev/kmsg
 }
 
 start_service
diff --git a/mbtk/rootfs/etc/mbtk/gsw_log_manage.sh b/mbtk/rootfs/etc/mbtk/gsw_log_manage.sh
new file mode 100755
index 0000000..3bc2488
--- /dev/null
+++ b/mbtk/rootfs/etc/mbtk/gsw_log_manage.sh
@@ -0,0 +1,435 @@
+#!/bin/sh
+LOGI() { echo "<6> LOG_MANAGE_INFO: $1" > /dev/kmsg; }
+LOGW() { echo "<4>LOG_MANAGE_WARN: $1" > /dev/kmsg; }
+LOGE() { echo "<3>LOG_MANAGE_ERROR: $1" > /dev/kmsg; }
+
+LOG_DIR="/media/var/log"
+G_LOG_DIR=""
+G_LOG_DIRS=""
+
+AP_LOG_MAX_SIZE=$(((300-10) * 1048576))   		# 300MB-10MB(radio_log.txt)
+CP_LOG_MAX_SIZE=$(((600-10) * 1048576))   		# 600MB-10MB(sdlog00x.sdl)
+CORE_LOG_MAX_SIZE=$((200 * 1048576)) 			# 200MB
+
+COUNTER_FILE="$LOG_DIR/counter.txt"  # 保存当前文件夹计数器值
+# ==================== Create log directory ====================
+
+create_log_dir() {
+    local dir="$1"
+    cd "$dir" || {
+        LOGE "create_log_dir: Failed to enter directory $dir"
+        return 1
+    }
+    
+    if [ ! -f "$COUNTER_FILE" ]; then
+        echo "1" > "$COUNTER_FILE"  # 从1开始
+        LOGI "create_log_dir: Created counter file: $COUNTER_FILE"
+    fi
+    
+    local current_counter=$(cat "$COUNTER_FILE")
+    
+    local new_folder
+    if [ "$current_counter" -lt 200 ]; then
+        new_folder=$((current_counter + 1))
+    else
+        new_folder=1
+    fi
+    
+    echo "$new_folder" > "$COUNTER_FILE"
+    LOGI "create_log_dir: Updated counter to: $new_folder"
+    
+    local formatted_folder=$(printf "%03d" "$new_folder")
+    local target_folder="LOG_FILE$formatted_folder"
+    
+    if [ -d "$target_folder" ]; then
+        LOGI "create_log_dir: Deleting existing folder $target_folder..."
+        rm -rf "$target_folder" || {
+            LOGI "create_log_dir: Failed to delete $target_folder"
+        }
+    fi
+	
+    if mkdir -p "$target_folder"; then
+        G_LOG_DIR="$dir/$target_folder"
+        LOGI "create_log_dir: Log directory created: $G_LOG_DIR"
+    else
+        mkdir -p "LOG_FILE001"
+        G_LOG_DIR="$dir/LOG_FILE001"
+        LOGE "create_log_dir: Fallback to LOG_FILE001 (create $target_folder failed)"
+    fi
+    
+    return 0
+}
+
+
+sort_log_dir() {
+	local log_folders=$(find "$LOG_DIR" -maxdepth 1 -type d -name "LOG_FILE[0-9][0-9][0-9]" 2>/dev/null)
+    local folder_nums=""
+    
+    for folder in $log_folders; do
+        local num=$(basename "$folder" | sed 's/LOG_FILE//' | sed 's/^0*//')
+        folder_nums="$folder_nums $num"
+    done
+    
+	local current_folder=$(basename "$G_LOG_DIR")
+    local current_num=$(echo "$current_folder" | sed 's/LOG_FILE//' | sed 's/^0*//')
+	
+    # 按照规则排序文件夹:先处理大于最新编号的(按升序),再处理小于等于的(按升序)
+    local sorted_folders=""
+    
+    # 1. 添加大于最新编号的文件夹(按升序)
+    for num in $(echo $folder_nums | tr ' ' '\n' | sort -n); do
+        if [ "$num" -gt "$current_num" ]; then
+            sorted_folders="$sorted_folders $LOG_DIR/LOG_FILE$(printf "%03d" $num)"
+        fi
+    done
+    
+    # 2. 添加小于等于最新编号的文件夹(按升序)
+    for num in $(echo $folder_nums | tr ' ' '\n' | sort -n); do
+        if [ "$num" -le "$current_num" ]; then
+            sorted_folders="$sorted_folders $LOG_DIR/LOG_FILE$(printf "%03d" $num)"
+        fi
+    done
+	
+	G_LOG_DIRS="$sorted_folders"
+	for folder in $G_LOG_DIRS; do
+        LOGI "create_log_dir: get LOG_FILES:$folder"
+	done
+	return 0
+}
+
+# ==================== Compress single file ====================
+tar_single_file() {
+    local file="$1"
+    local dir=$(dirname "$file")
+    local filename=$(basename "$file")
+    
+    [ ! -f "$file" ] && {
+        LOGE "tar_single_file: File '$file' does not exist"
+        return 1
+    }
+    
+    local compressed_file="${dir}/${filename}.tar.gz"
+    
+    # Low priority compression (reduce CPU usage)
+    (cd "$dir" && nice -n 19 tar -czf "$compressed_file" "$filename") || {
+        LOGE "tar_single_file: Failed to compress $file"
+        return 2
+    }
+    
+    rm -f "$file" || {
+        LOGE "tar_single_file: Failed to delete original file $file"
+        return 3
+    }
+    
+    LOGI "tar_single_file: Compression completed: $compressed_file"
+    echo "$compressed_file"
+    return 0
+}
+
+
+# ==================== Get AP log compressed filename ====================
+get_ap_log_tar() {
+    local radio_tar_files=$(find "$1" -maxdepth 1 -type f -name 'radio_log.txt.*.tar.gz' | sed -E 's/.*radio_log.txt.([0-9]+).tar.gz/\1/')
+    local new_number=1
+    
+    if [ -n "$radio_tar_files" ]; then
+        local last_number=$(echo "$radio_tar_files" | sort -n | tail -n 1)
+        new_number=$((last_number + 1))
+    fi
+    
+    echo "radio_log.txt.${new_number}.tar.gz"
+}
+
+
+# ==================== Get inactive CP logs ====================
+get_inactive_cplogs_by_name() {
+    local dir="$1"
+    cd "$dir" || {
+        LOGE "get_inactive_cplogs_by_name: Failed to enter directory $dir"
+        return 1
+    }
+    
+    local temp_file=$(mktemp)
+    ls sdlog[0-9][0-9][0-9].sdl 2>/dev/null | sort -t 'g' -k2 -n > "$temp_file"
+    
+    local total=$(wc -l < "$temp_file")
+    if [ "$total" -gt 1 ]; then
+        head -n 1 "$temp_file"  # Only take one file
+    fi
+    
+    rm -f "$temp_file"
+    return 0
+}
+
+
+process_single_log() {
+    local file_pattern="$1"
+    local search_dir="$2"
+    local regex_pattern="$3"
+    
+    cd "$search_dir" || {
+        LOGE "process_single_log: Failed to enter directory $search_dir"
+        return 1
+    }
+    
+    local file=""
+    case "$file_pattern" in
+        "ap_log")
+            file=$(find . -maxdepth 1 -type f -regex "$regex_pattern" | head -n 1)
+            ;;
+        "cp_log")
+            file=$(get_inactive_cplogs_by_name "$search_dir")
+            ;;
+        "core_dump_log")
+            file=$(find "$search_dir" -type f | head -n 1)
+            ;;
+        *)
+            LOGE "process_single_log: Unknown file pattern '$file_pattern'"
+            return 1
+            ;;
+    esac
+    
+    [ -z "$file" ] && {
+        LOGI "process_single_log: No $file_pattern type files to process"
+        return 0
+    }
+    
+    file="${file#./}"  # Remove leading ./
+    LOGI "process_single_log: Found file: $file"
+    
+    local full_file_path
+    if [ "$file_pattern" = "core_dump_log" ]; then
+        full_file_path="$file"
+    else
+        full_file_path="$search_dir/$file"
+    fi
+    
+    local compressed_file=$(tar_single_file "$full_file_path")
+    local ret=$?
+    if [ $ret -ne 0 ]; then
+        LOGE "process_single_log: Compression of $file failed with code $ret"
+        return $ret
+    fi
+    
+    if [ -n "$G_LOG_DIR" ] && [ -d "$G_LOG_DIR" ]; then
+        if [ "$file_pattern" = "ap_log" ]; then
+            local new_file=$(get_ap_log_tar "$G_LOG_DIR")
+            mv "$compressed_file" "${G_LOG_DIR}/${new_file}" || {
+                LOGE "process_single_log: Failed to move $new_file to $G_LOG_DIR"
+                return 1
+            }
+            LOGI "process_single_log: AP log moved to: $G_LOG_DIR/$new_file"
+        else
+            mv "$compressed_file" "$G_LOG_DIR/" || {
+                LOGE "process_single_log: Failed to move $compressed_file to $G_LOG_DIR"
+                return 1
+            }
+            LOGI "process_single_log: Log moved to: $G_LOG_DIR/$(basename "$compressed_file")"
+        fi
+    fi
+    
+    return 0
+}
+
+
+# ==================== Clean up files by type ====================
+cleanup_by_type() {
+    local type_name="$1"
+    local pattern="$2"
+    local max_size="$3"
+    local sort_method="$4"
+	
+    LOGI "cleanup_by_type: Starting check for $type_name files"
+    
+    # Calculate total size of all files of this type
+    local all_files=""
+    local total_size=0
+    local file_size_kb=0
+    for folder in $G_LOG_DIRS; do
+        local files=$(find "$folder/" -type f -name "$pattern" 2>/dev/null | eval "$sort_method")
+        
+        if [ -n "$files" ]; then
+            for file in $files; do
+                local size=$(ls -l "$file" | awk '{print $5}')       
+				file_size_kb=$((size / 1024))			
+				LOGI "cleanup_by_type: Found $type_name file: $file size:$file_size_kb KB"
+                total_size=$((total_size + size))
+                all_files="$all_files\n$size $file"
+            done
+        fi
+    done
+	
+    local total_mb=$((total_size / 1048576))
+    local max_mb=$((max_size / 1048576))
+	local total_kb=$((total_size / 1024))
+    local max_kb=$((max_size / 1024))
+	
+    LOGI "cleanup_by_type: $type_name total size: $total_mb MB $total_kb KB (threshold: $max_mb MB  $max_kb KB)"
+	
+    if [ "$total_size" -le "$max_size" ]; then
+        LOGI "cleanup_by_type: $type_name below threshold, no need cleanup"
+        return 0
+    fi
+    
+    # Exceeds threshold, start cleaning up (oldest folders first)
+    LOGI "cleanup_by_type: $type_name exceeds threshold, starting cleanup..."
+    local current_size=$total_size
+    
+    for folder in $G_LOG_DIRS; do
+        local folder_files=$(echo -e "$all_files" | grep "$folder" | awk '{print $2}')
+        
+        for file in $folder_files; do
+            local file_size=$(ls -l "$file" | awk '{print $5}')
+            current_size=$((current_size - file_size))
+            
+            rm -f "$file" || {
+                LOGE "cleanup_by_type: Failed to delete $file"
+                continue
+            }
+            LOGI "cleanup_by_type: Deleted $(basename "$file"), freed $((file_size / 1048576)) MB"
+            
+            # Stop if below threshold after deletion
+            if [ "$current_size" -le "$max_size" ]; then
+                LOGI "cleanup_by_type: $type_name cleanup completed, current total size $((current_size / 1048576)) MB"
+                return 0
+            fi
+        done
+    done
+    
+    LOGI "cleanup_by_type: All matching files deleted, current total size $((current_size / 1048576)) MB"
+    return 0
+}
+
+
+# ==================== Log processing functions ====================
+ap_log_process() {    
+	LOGI "======================= Processing AP log ==================================="
+    process_single_log "ap_log" "$LOG_DIR" '.*/radio_log\.txt\.[0-9]\{1,3\}$'
+}
+
+cp_log_process() {
+    LOGI "======================= Processing CP log ==================================="
+	local search_dir="$1"
+    
+    cd "$search_dir" || {
+        LOGE "cp_log_process: Failed to enter directory $search_dir"
+        return 1
+    }
+    
+    local CP_Log_folder=$(find . -maxdepth 1 -type d -regex '.*/Log[0-9]\{3\}$' | head -n 1)
+    [ -z "$CP_Log_folder" ] && {
+        LOGE "cp_log_process: No matching Log folder found"
+        return 1
+    }
+    
+    CP_Log_folder="${CP_Log_folder#./}"
+    LOGI "cp_log_process: Found CP log folder: $search_dir/$CP_Log_folder"
+    process_single_log "cp_log" "$search_dir/$CP_Log_folder" ''
+}
+
+core_dump_log_process() {
+    LOGI "==================== Processing core dump log ================================"
+	local core_dump_folder="${1}/modem_dump"
+    
+    [ ! -d "$core_dump_folder" ] && {
+        LOGE "core_dump_log_process: Core dump directory does not exist - $core_dump_folder"
+        return 1
+    }
+    process_single_log "core_dump_log" "$core_dump_folder" ''
+}
+
+
+
+# ==================== Main loop ====================
+gsw_log_manage() {
+    while true; do
+        sleep 90  # Execute every 90 seconds
+        
+        # Process AP log
+        ap_log_process
+        sleep 2
+        
+        # Process CP log
+        cp_log_process "$LOG_DIR"
+        sleep 2
+        
+        # Process core dump log
+        core_dump_log_process "$LOG_DIR"
+        sleep 2
+        
+        # Clean up files by type
+        LOGI "======================= Starting cleanup by file type ======================="
+        cleanup_by_type "AP log" "radio_log.txt.*.tar.gz" "$AP_LOG_MAX_SIZE" "sort -t '.' -k3 -n"
+        cleanup_by_type "CP log" "sdlog*.sdl.tar.gz" "$CP_LOG_MAX_SIZE"	"sort -t 'g' -k2 -n"
+        cleanup_by_type "Core_Dump log" "coredump-*.tar.gz" "$CORE_LOG_MAX_SIZE" ""
+        
+        LOGI "===== Current round of log processing completed, waiting for next round ====="
+    done
+}
+
+#处理上一次开机中,遗留的cp log文件,将其压缩并移动到上一个G_LOG_DIR文件夹中
+cp_log_previous_boot_process() {
+    if [ ! -f "$COUNTER_FILE" ]; then
+        LOGI "cp_log_previous_boot_process: $COUNTER_FILE is not exist, returning"
+        return 0
+    fi
+    
+    local previous_counter=$(cat "$COUNTER_FILE")
+    local formatted_folder=$(printf "%03d" "$previous_counter")
+    local target_folder="LOG_FILE$formatted_folder"
+    local compressed_file=""
+    target_folder="$1/$target_folder"
+    
+    local log000_dir="$1/Log000"
+    
+    if [ ! -d "$log000_dir" ]; then
+        LOGE "Log000 directory not found: $log000_dir"
+        return 0
+    fi
+    
+    cd "$log000_dir" || {
+        LOGE "Failed to enter directory: $log000_dir"
+        return 1
+    }
+    
+    
+    local files_to_tar_move=$(find . -maxdepth 1 -type f ! -name "sdlog000.sdl")
+    
+    if [ -n "$files_to_tar_move" ]; then
+        for file in $files_to_tar_move; do
+            file="${file#./}"
+            compressed_file=$(tar_single_file "$file")
+            if [ ! -f "$compressed_file" ]; then
+                compressed_file="$log000_dir/$compressed_file"
+            fi
+            
+            mv "$compressed_file" "$target_folder/" || {
+                LOGE "Failed to move $compressed_file to $target_folder"
+                return 1
+            }
+            LOGI "Moved $file (compressed) to $target_folder"
+        done
+    else
+        LOGI "cp_log_previous_boot_process: No files to process in $log000_dir (excluding sdlog000.sdl)"
+    fi
+    
+    LOGI "cp_log_previous_boot_process: completed successfully"
+    return 0
+}
+
+(
+	#开机延迟200秒执行
+	sleep 200 ; \
+	#处理上一次开机遗留的cp log(sdlog000.sdl会被覆盖)
+	cp_log_previous_boot_process "$LOG_DIR" ; \
+	#创建LOG存储文件夹
+	create_log_dir "$LOG_DIR" ; \
+	#对LOG存储文件夹进行排序
+	sort_log_dir ; \
+	LOGI "Initial functions completed, starting gsw_log_manage..."
+
+	while ! gsw_log_manage; do
+		echo "Restarting gsw_log_manage ..."
+		sleep 1
+	done
+) &
diff --git a/mbtk/rootfs/etc/mbtk/mbtk_log.json b/mbtk/rootfs/etc/mbtk/mbtk_log.json
index 0b65b34..503c562 100755
--- a/mbtk/rootfs/etc/mbtk/mbtk_log.json
+++ b/mbtk/rootfs/etc/mbtk/mbtk_log.json
@@ -5,7 +5,7 @@
     "buffer_list" :
     [
         {
-            "enable": 1,
+            "enable": 0,
             /* (mandatory) alternate ring buffer name, 'main', 'system', 'events' */
             "name" : "syslog",
             /* log output format : log type, time, pid, tid, tag, msg */
@@ -43,9 +43,9 @@
             "log_file":"/media/var/log/radio_log.txt",
 	    "emmc_protect": 0,
             /* (optional) rotate log every kbytes, default is unlimit */
-            "rotate_file_size":  1024,
+            "rotate_file_size":  10240,
             /* (optional) max number of rotated logs, -1 is unlimit */
-            "rotate_file_count": 8,
+            "rotate_file_count": 20,
 
             /* (optional) log format, default or csv */
             "log_format":"default",
diff --git a/mbtk/test/libgsw_lib/gsw_log_check.c b/mbtk/test/libgsw_lib/gsw_log_check.c
deleted file mode 100755
index 510b815..0000000
--- a/mbtk/test/libgsw_lib/gsw_log_check.c
+++ /dev/null
@@ -1,604 +0,0 @@
-#include <stdio.h>

-#include <stdlib.h>

-#include <string.h>

-#include <dirent.h>

-#include <regex.h>

-#include <sys/stat.h>

-#include <sys/time.h>

-#include <time.h>

-#include <limits.h>

-#include <fcntl.h>

-#include <unistd.h>

-#include <ctype.h>

-#include <dlfcn.h>

-

-

-typedef void (*mbtk_log)(int level, const char *format,...);

-static void *handle = NULL;

-static mbtk_log fun_ptr_log = NULL;

-#define LIB_PATH				 "/lib/libmbtk_lib.so"

-#define LOG_LEVLE_CONFIG_FILE 	 "/etc/telinit"

-#define MAX_FILES 500

-#define MAX_PATH  100

-#define CP_LOG_PATH  	"/media/var/log"

-#define DUMP_LOG_PATH  	"/media/var/log/modem_dump"

-#define EMMC_HEALTH 	"/sys/kernel/debug/mmc0/mmc0:0001/health"

-#define CP_LOG_MAX_SIZE 	(600 * 1024 * 1024)

-#define DUMP_LOG_MAX_SIZE 	(100 * 1024 * 1024)

-#define SEVEN_DAYS_SECONDS  (7 * 24 * 60 * 60)

-

-#ifndef LOG_ERR_LEVEL

-#define LOG_ERR_LEVEL  3      /* error conditions */

-#endif

-#ifndef LOG_WARN_LEVEL

-#define LOG_WARN_LEVEL 4   /* warning conditions */

-#endif

-#ifndef LOG_INFO_LEVEL

-#define LOG_INFO_LEVEL 6      /* informational */

-#endif

-#ifndef LOG_DEBUG_LEVEL

-#define LOG_DEBUG_LEVEL 7     /* debug-level messages */

-#endif

-#ifndef LOG_VERBOSE_LEVEL

-#define LOG_VERBOSE_LEVEL 8

-#endif

-

-#define LOGV(fmt, args ...) \

-    do{ \

-        char *file_ptr_1001 = __FILE__; \

-        char *ptr_1001 = file_ptr_1001 + strlen(file_ptr_1001) - 1;   \

-        char line_1001[10] = {0}; \

-        sprintf(line_1001, "%d", __LINE__); \

-        while(ptr_1001 >= file_ptr_1001 && *ptr_1001){ \

-            if(*ptr_1001 == '/') \

-                 break; \

-            ptr_1001--; \

-        } \

-        fun_ptr_log(LOG_INFO_LEVEL, "%s#%s: [log_check]" fmt, ptr_1001 + 1, line_1001, ##args); \

-    } while(0)

-

-#define LOGI(fmt, args...) \

-    do{ \

-        char *file_ptr_1001 = __FILE__; \

-        char *ptr_1001 = file_ptr_1001 + strlen(file_ptr_1001) - 1;   \

-        char line_1001[10] = {0}; \

-        sprintf(line_1001, "%d", __LINE__); \

-        while(ptr_1001 >= file_ptr_1001 && *ptr_1001){ \

-            if(*ptr_1001 == '/') \

-                 break; \

-            ptr_1001--; \

-        } \

-        fun_ptr_log(LOG_INFO_LEVEL, "%s#%s: [log_check]" fmt, ptr_1001 + 1, line_1001, ##args); \

-    } while(0)

-

-#define LOGD(fmt, args...) \

-    do{ \

-        char *file_ptr_1001 = __FILE__; \

-        char *ptr_1001 = file_ptr_1001 + strlen(file_ptr_1001) - 1;   \

-        char line_1001[10] = {0}; \

-        sprintf(line_1001, "%d", __LINE__); \

-        while(ptr_1001 >= file_ptr_1001 && *ptr_1001){ \

-            if(*ptr_1001 == '/') \

-                 break; \

-            ptr_1001--; \

-        } \

-        fun_ptr_log(LOG_INFO_LEVEL, "%s#%s: [log_check]" fmt, ptr_1001 + 1, line_1001, ##args); \

-    } while(0)

-

-#define LOGW(fmt, args...) \

-    do{ \

-        char *file_ptr_1001 = __FILE__; \

-        char *ptr_1001 = file_ptr_1001 + strlen(file_ptr_1001) - 1;   \

-        char line_1001[10] = {0}; \

-        sprintf(line_1001, "%d", __LINE__); \

-        while(ptr_1001 >= file_ptr_1001 && *ptr_1001){ \

-            if(*ptr_1001 == '/') \

-                 break; \

-            ptr_1001--; \

-        } \

-        fun_ptr_log(LOG_INFO_LEVEL, "%s#%s: [log_check]" fmt, ptr_1001 + 1, line_1001, ##args); \

-    } while(0)

-

-#define LOGE(fmt, args...) \

-    do{ \

-		char *file_ptr_1001 = __FILE__; \

-		char *ptr_1001 = file_ptr_1001 + strlen(file_ptr_1001) - 1;   \

-		char line_1001[10] = {0}; \

-		sprintf(line_1001, "%d", __LINE__); \

-		while(ptr_1001 >= file_ptr_1001 && *ptr_1001){ \

-			if(*ptr_1001 == '/') \

-				break; \

-			ptr_1001--; \

-		} \

-		fun_ptr_log(LOG_INFO_LEVEL, "%s#%s: [log_check]" fmt, ptr_1001 + 1, line_1001, ##args); \

-	} while(0)

-

-int32_t init_handle()

-{

-	handle = dlopen(LIB_PATH, RTLD_NOW);

-	if(handle == NULL)

-	{

-		return -1;

-	}

-	if(fun_ptr_log == NULL)

-	{

-		fun_ptr_log = (mbtk_log)dlsym(handle, "mbtk_log");

-		if(fun_ptr_log ==  NULL)

-		{

-			return -1;

-		}

-	}

-	return 0;

-}

-

-typedef struct {

-	char name[128];

-	time_t mtime;

-	off_t size;

-} LogDir;

-

-int compare_mtime(const void *a, const void *b) {

-	LogDir *dirA = (LogDir *)a;

-	LogDir *dirB = (LogDir *)b;

-	return (dirA->mtime - dirB->mtime); // 升序排序

-}

-

-static int get_cp_log_folder(char *path, LogDir *dirs, int *dirs_count)

-{

-    DIR *dp    = NULL;

-	DIR *subdp = NULL;

-	struct dirent *entry;

-	struct dirent *subentry;

-	struct stat st;

-	regex_t regex;

-	int 	count = 0;

-	int  	folder_size = 0;

-	int  	total_size  = 0;

-	char 	full_path[1024];

-	char 	temp_path[1024];

-	

-    // 编译正则表达式:^Log[0-9]{3}.*

-    if (regcomp(&regex, "^Log[0-9]{3}.*", REG_EXTENDED) != 0) 

-	{

-		fprintf(stderr, "Failed to compile regex.\n");

-		return -1;

-		}

-

-	dp = opendir(path);

-	if (dp == NULL) 

-	{

-		perror("opendir");

-		return -1;

-    }

-

-    while ((entry = readdir(dp)) != NULL) 

-	{

-		if (regexec(&regex, entry->d_name, 0, NULL, 0) == 0)   //entr:Log00x

-		{

-			snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);

-			strncpy(dirs[count].name, full_path, sizeof(dirs[count].name));

-			//printf("flod:%s \n", full_path);

-

-			if (strstr(full_path, "tar.gz") != NULL)    		//tar file

-			{

-				if (lstat(full_path, &st) < 0)

-				{

-					perror("lstat");

-				}	

-				folder_size += st.st_size;

-				dirs[count].mtime = st.st_mtime;

-

-			}

-			else 

-			{

-				subdp = opendir(full_path); 					//Log00x Folder

-				if (NULL == subdp)

-				{

-					LOGE("cant open:%s\n", full_path);

-					continue;

-				}

-				

-				while ((subentry = readdir(subdp)) != NULL) 

-				{

-					if (strcmp(subentry->d_name, ".") == 0 || strcmp(subentry->d_name, "..") == 0)

-						continue;

-					

-					//snprintf(temp_path, sizeof(temp_path), "%s/%s", full_path, subentry->d_name);

-					temp_path[0] = '\0';

-					strncat(temp_path, full_path, sizeof(temp_path) - 1);

-					strncat(temp_path, "/", sizeof(temp_path) - strlen(temp_path) - 1);

-					strncat(temp_path, subentry->d_name, sizeof(temp_path) - strlen(temp_path) - 1);

-					

-					//printf("file:%s \n", temp_path);

-	

-					if (lstat(temp_path, &st) < 0) 

-					{

-						perror("lstat");

-						continue;

-					}

-					if (S_ISREG(st.st_mode)) 

-					{

-						folder_size += st.st_size;

-						dirs[count].mtime = st.st_mtime;

-					}

-				

-				}

-				if(NULL != subdp)

-					closedir(subdp);

-

-			}

-			dirs[count].size = folder_size;

-			total_size += folder_size;

-			folder_size = 0;

-			count++;

-			

-			if (count >= MAX_FILES) 

-			{

-				fprintf(stderr, "Too many matching directories, increase MAX_DIRS.\n");

-				break;

-			}

-		}

-	}

-	

-	closedir(dp);

-	regfree(&regex);

-	qsort(dirs, count, sizeof(LogDir), compare_mtime);

-	

-	*dirs_count = count;

-	return total_size;

-

-}

-

-static int get_dump_log_folder(char *path, LogDir *files, int *dirs_count)

-{

-	

-	DIR *dp = NULL;

-	struct dirent *entry;

-	char full_path[4096];

-	int  total_size = 0;

-	int  count = 0;

-	struct stat st;

-

-	dp = opendir(path);

-	if (NULL == dp) 

-	{

-		perror("opendir");

-		return -1;

-	}

-

-    while ((entry = readdir(dp)) != NULL)

-	{

-		if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)

-			continue;

-		snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);

-

-		

-

-		

-		//printf("file:%s \n", full_path);

-		

-		if (lstat(full_path, &st) < 0) {

-			perror("lstat");

-			continue;

-		}

-		if (S_ISREG(st.st_mode)) {

-			total_size += st.st_size;			

-			strncpy(files[count].name, full_path, sizeof(files[count].name));

-			files[count].size = st.st_size;

-			files[count++].mtime = st.st_mtime;

-		}

-    }

-	if(NULL != dp)

-		closedir(dp);

-	*dirs_count = count;

-	

-	qsort(files, count, sizeof(LogDir), compare_mtime);

-	return total_size;

-

-}

-

-

-int get_emmc_health(char *path)

-{

-	char buffer[1024];

-	int 	result = -1;

-	int 	i = 0;

-	int fd = open(path, O_RDONLY);

-	if (fd == -1)

-	{

-		LOGE("can not open health node");

-		return -1;

-	}

-

-	ssize_t bytes_read = read(fd, buffer, sizeof(buffer) - 1);

-	if (bytes_read > 0) 

-	{

-		buffer[bytes_read] = '\0';

-		LOGI("emmc health node string:\n%s len:%d\n", buffer, bytes_read);

-	}

-	close(fd);

-	

-	for(i = 0; i < bytes_read; i++)

-	{

-		if('-' == buffer[i])

-		{

-			char num_str[4] = {buffer[i+1], buffer[i+2], buffer[i+3], '\0'};

-			result = atoi(num_str);

-			LOGI("emmc health %d\n", result);

-			break;

-		}

-	}

-	

-	return result;

-

-}

-

-int set_log_level(const char *log_level)

-{

-	char 	command[256] = {0};

-	char 	*log_levl_param[6] = {"default", "cp_load", "atcmdsrv", "ciClientStubTas", "nvmproxy", "rild"};

-	int 	i = 0;

-	

-	for(i = 0; i < 6; i++)

-	{

-		snprintf(command, sizeof(command), 

-		         "sed -i 's/\\(setprop sys.%s.loglevel \\)\\S*/\\1%s/' %s",

-		         log_levl_param[i], log_level, LOG_LEVLE_CONFIG_FILE);

-		

-		int result = system(command);

-		if (result != 0) 

-		{

-		    LOGE("command execution failed.\n", command);

-		    return -1;

-		}

-	}

-	

-	return 0;

-}

-

-

-

-int is_modified_within_7_days(LogDir dir) 

-{

-	time_t now = time(NULL);

-	time_t mtime = dir.mtime;

-

-	// 计算时间差

-	double diff = difftime(now, mtime);

-

-	if (diff <= SEVEN_DAYS_SECONDS) 

-	{

-		return 1;

-	} else {

-		return 0;

-	}

-}

-

-int tar_log_file(const char *path_name, time_t mtime)

-{

-	char command[256] = {0};

-	struct timeval times[2];

-	char tar_file[128];

-	struct stat st;

-    time_t now;

-    struct tm *tm_info;

-    char time_str[64];

-	int ret; 

-	

-	LOGI("input log file: %s\n", path_name);

-	time(&now);

-	tm_info = localtime(&now);

-	strftime(time_str, sizeof(time_str), "%Y-%m-%d-%H:%M:%S", tm_info);

-	snprintf(tar_file, sizeof(tar_file)," %s-%s.tar.gz", path_name, time_str);

-	

-	LOGI("input log file: %s\n", tar_file);

-	

-	snprintf(command, sizeof(command), "tar -czvf %s %s", tar_file, path_name);

-	ret = system(command);

-	if (ret != 0) 

-	{

-		LOGE("command execution failed.\n", command);

-		return -1;

-	}

-

-

-	if (lstat(tar_file, &st) < 0) 

-	{

-	    return -1;

-	}

-	times[0].tv_sec = st.st_atime;

-	times[0].tv_usec = 0;

-	times[1].tv_sec = mtime;

-	times[1].tv_usec = 0;

-

-	if (utimes(tar_file, times) < 0)		

-	{

-	    return -1;

-	}	//update tar file mtime

-	

-	return 0;

-

-}

-

-

-int main(int argc, char* argv[])

-{

-	int health;

-	LogDir cp_dirs[MAX_FILES];

-	LogDir dump_files[MAX_FILES];

-	int cp_dirs_count = 0;

-	int dump_files_count = 0;

-	int i = 0;

-	int ret = 0;

-	char command[128] = {0};

-	int total_size = 0;

-	int modify_7day;

-	init_handle();

-	

-	health = get_emmc_health(EMMC_HEALTH);

-	if(health != -1)

-	{	

-		if(health >= 50 && health < 70)

-		{

-			ret = set_log_level("5");			//warn

-			if(ret != 0)

-				LOGE("set log level error\n");

-		}

-		

-		if(health >= 70)

-		{

-			ret = set_log_level("0");				

-			if(ret != 0)

-				LOGE("set log level error\n");

-		}

-	}

-	else

-	{

-		LOGE("get emmc health error\n");

-	}

-

-	while(1)

-	{

-		i = 0;

-		total_size = get_cp_log_folder(CP_LOG_PATH, cp_dirs, &cp_dirs_count);

-		LOGI("module %s files size:%d MB\n",CP_LOG_PATH, (total_size/1024)/1024);

-		while(total_size >= CP_LOG_MAX_SIZE)

-		{

-			LOGI("Exceed capacity limit:%d MB  now:%d MB\n", (CP_LOG_MAX_SIZE/1024)/1024, (total_size/1024)/1024);

-			if(i >= cp_dirs_count)

-			{

-				LOGE("No more files that can be compressed\n");

-				break;

-			}

-			modify_7day = is_modified_within_7_days(cp_dirs[i]);

-			if(modify_7day == 0)

-			{

-				//Delete files created for more than 7 days

-				//snprintf(command, sizeof(command), "rm -rf %s", cp_dirs[i].name);

-				command[0] = '\0';

-				strncat(command, "rm -rf ", sizeof(command) - 1);

-				strncat(command, cp_dirs[i].name, sizeof(command) - strlen(command) - 1);

-				

-				LOGI("Delete files:%s created for more than 7 days\n", cp_dirs[i].name);

-				ret = system(command);

-				if (ret != 0) 

-				{

-					LOGE("command execution failed.\n", command);

-					return -1;

-				}

-				LOGI("Execute the command:%s\n", command);

-			}

-			

-			if(modify_7day == 1) 

-			{

-				if(strstr(cp_dirs[i].name, "tar.gz") != NULL)

-				{

-					LOGI("Tar file:%s already exists, No more compression at once\n", cp_dirs[i].name);

-					i++;

-					continue;

-				}

-

-				tar_log_file(cp_dirs[i].name, cp_dirs[i].mtime);

-

-				//snprintf(command, sizeof(command), "rm -rf %s", cp_dirs[i].name);

-				command[0] = '\0';

-				strncat(command, "rm -rf ", sizeof(command) - 1);

-				strncat(command, cp_dirs[i].name, sizeof(command) - strlen(command) - 1);

-				

-				LOGI("del folder command:%s\n", command);

-				ret = system(command);

-				if (ret != 0) 

-				{

-					LOGE("command execution failed.\n", command);

-					return -1;

-				}

-			}

-			i++;

-			total_size = get_cp_log_folder(CP_LOG_PATH, cp_dirs, &cp_dirs_count);

-			sleep(2);

-

-		}

-		

-		i = 0;

-		total_size = get_dump_log_folder(DUMP_LOG_PATH, dump_files, &dump_files_count);

-		LOGI("module %s files size:%d MB\n",DUMP_LOG_PATH, (total_size/1024)/1024);

-		while(total_size >= DUMP_LOG_MAX_SIZE)

-		{

-			LOGI("Exceed capacity limit:%d MB  now:%d MB\n", (DUMP_LOG_MAX_SIZE/1024)/1024, (total_size/1024)/1024);

-			if(i >= dump_files_count) 

-			{

-				LOGE("No more files that can be compressed\n");

-				break;

-			}

-			modify_7day = is_modified_within_7_days(dump_files[i]);

-			if(modify_7day == 0) 

-			{			

-				//del timeout file

-				//snprintf(command, sizeof(command), "rm -rf %s", dump_files[i].name);

-				command[0] = '\0'; 

-				strncat(command, "rm -rf ", sizeof(command) - 1);

-				strncat(command, cp_dirs[i].name, sizeof(command) - strlen(command) - 1);

-

-				LOGI("command:%s, total_size:%d \n", command, total_size);

-				ret = system(command);

-				if (ret != 0) 

-				{

-					LOGE("command execution failed.\n", command);

-					return -1;

-				}

-			}

-			if(modify_7day == 1) 

-			{

-				if(strstr(dump_files[i].name, "tar.gz") != NULL)

-				{

-					LOGI("Tar file:%s already exists, No more compression at once\n", dump_files[i].name);

-					i++;

-					continue;

-				}

-				tar_log_file(dump_files[i].name, dump_files[i].mtime);

-				

-				//del source file

-				//snprintf(command, sizeof(command), "rm -rf %s", dump_files[i].name);

-				command[0] = '\0';

-				strncat(command, "rm -rf ", sizeof(command) - 1);

-				strncat(command, dump_files[i].name, sizeof(command) - strlen(command) - 1);

-				

-				LOGI("del folder command:%s\n", command);

-				ret = system(command);

-				if (ret != 0) 

-				{

-					LOGE("command execution failed.\n", command);

-					return -1;

-				}

-			}

-			i++;

-			total_size = get_dump_log_folder(DUMP_LOG_PATH, dump_files, &dump_files_count);

-			sleep(2);

-		}

-

-		sleep(60);

-	

-#if 0

-		for(i = 0; i < cp_dirs_count && cp_dirs_count < MAX_FILES; i++) {

-			struct tm *tm_info = localtime(&cp_dirs[i].mtime);

-			strftime(timebuf, sizeof(timebuf), "%Y-%m-%d %H:%M:%S", tm_info);

-			printf("folder:%s, files:%ld, time:%s\n", cp_dirs[i].name, cp_dirs[i].size, timebuf);

-		}

-		

-	

-		

-		for(i = 0; i < dump_files_count && dump_files_count < MAX_FILES; i++) {

-			struct tm *tm_info = localtime(&dump_files[i].mtime);

-			strftime(timebuf, sizeof(timebuf), "%Y-%m-%d %H:%M:%S", tm_info);

-			printf("folder:%s, files:%ld, time:%s\n", dump_files[i].name, dump_files[i].size, timebuf);

-		}

-#endif

-		

-	}

-	

-	return 0;

-}

-

-

-

-