#!/bin/bash

if [[ "$1" == "help" || "$1" == "--help" || "$1" == "-h" ]]; then
    echo -e "$0:\n"    \
    "Usage: $0 <'YYYY-MM-DD HH:MM:SS'> [<jq_command>]\n"    \
    "Description: Search for the last record in the pear_monitor.log file that matches the specified time.\n"    \
    "             The time format is 'YYYY-MM-DD HH:MM:SS'.\n"    \
    "             If jq_command is specified, the output will be processed by jq.\n"    \
    "             If jq_command is not specified, the output will be the full record.\n"    \
    "Example: $0 '2020-12-31 23:59:59'\n"    \
    "         $0 '2020-12-31 23:59:59' .plugins\n"    \
    "         $0 '2020-12-31 23:59:59' '{plugins: .plugins}\n"    \
    "         $0 '2020-12-31 23:59:59' '.plugins | .[] | select(.nic == \"ppp0\")'\n" 
fi

# 检查输入参数
if [[ "$#" == 1 ]]; then
    JQ_COMMAND=""
elif [[ "$#" == 2 ]]; then
    JQ_COMMAND="$2"
else
    echo "Usage: $0 <'YYYY-MM-DD HH:MM:SS'> [<jq_command>]"
    exit 1
fi

LOG_FILE="pear_monitor.log"
END_TIME="$1"

# 获取所有日志文件的路径
LOG_PATHS="$(jq -r '.storage[]' /etc/pear/pear_monitor/config.json) /"
LOG_FILES=""
for LOG_PATH in $LOG_PATHS; do
    LOG_FILES="${LOG_FILES} $(find ${LOG_PATH}/.pear/var/log/pear/ -name ${LOG_FILE})"
done
LOG_FILES=$(echo "$LOG_FILES" | sed 's/ //')
echo $LOG_FILES

# 检查输入时间格式（YYYY-MM-DD HH:MM:SS）
if ! [[ $END_TIME =~ ^[2][0][0-9][0-9]-[0-1][0-9]-[0-3][0-9]\ [0-2][0-9]:[0-5][0-9]:[0-5][0-9]$ ]]; then
    echo "Invalid date format. Please use YYYY-MM-DD HH:MM:SS."
    exit 1
fi



# 将结束时间转换为 Unix 时间戳
END_TIMESTAMP=$(date -d "$END_TIME" '+%s')

# 检查日期转换是否成功
if [ $? -ne 0 ]; then
    echo "Invalid date format. Please use 'YYYY-MM-DD HH:MM:SS'."
    exit 1
fi

# 在所有日志文件中搜索最后一条符合条件的记录
full_record=$(sudo awk -v end_timestamp="$END_TIMESTAMP" '
    function to_timestamp(date, time) {
        gsub(/-/, " ", date);
        gsub(/:/, " ", time);
        return mktime(date " " time);
    }
    /pear_update_stat [0-9]+ INFO\[[0-9]\]: request: {.*data.*:/ { 
        current_timestamp = to_timestamp($1, $2);
        if (current_timestamp <= end_timestamp) {
            if (last_record == "" || current_timestamp > last_record_timestamp) {
                last_record = $0
                last_record_timestamp = current_timestamp
            }
        }
    }
    END {
        if (last_record != "") {
            print last_record
        } else {
            print "No valid record found"
        }
    }
' ${LOG_FILES})

# 检查是否找到有效记录
if [[ $full_record == "No valid record found" ]]; then
    echo "No valid record found"
    exit 1
fi

# 分割字符串以提取所需部分
delimiter='{"data":'
extracted_data="${full_record#*$delimiter}"
deleted_part="${full_record%"$delimiter$extracted_data"}"

echo "$delimiter$extracted_data" | jq -r '.data' | jq . | jq "$JQ_COMMAND"
echo "$deleted_part"
