local uuid=`uci get auto_backup.schedule.uuid`
local path=`uci get auto_backup.schedule.path`
local retention=`uci get auto_backup.schedule.retention`
local max_num_of_files=`uci get auto_backup.schedule.max_num_of_files`
local mntdir=`lua -e "print(require 'luci.model.usbshare'.CfgParser():get_volumn(\"$uuid\").mntdir)"`
local real_path="${mntdir}${path:2}"
local config=`uci get auto_backup.schedule.config`
local log=`uci get auto_backup.schedule.log`
local host_name=`cat /proc/sys/kernel/hostname`
local config_length=$((${#host_name}+7))
local log_length=$((${#host_name}+11))

local CONFIG_TMP="/tmp/config.bin"
local BACKUP_TMP="/tmp/backup.tar.gz"
local BACKUP_CRY="/tmp/backup.cry"

if [ -x "${real_path}" ]; then
    local config_file_count=0
    local log_file_count=0

    # 根据配置参数清除数天之前的文件
    for file in `ls -lt "${real_path}" |grep ^- |awk '{print $9}'`
    do
        if [ ${#file} -gt 15 ] && [ ${file:0:$config_length} == "backup-"$host_name ] && [ ${file##*.} == "bin" ] && [ $config == "on" ]; then
            local file_time=`date +%s -r "${real_path}"/"${file}"`
            local now=`date +%s`
            let diff=$(($now-$file_time))
            if [ $diff -gt $(($retention*60*60*24)) ]; then
                rm -f "${real_path}"/"${file}"
            else
                config_file_count=$(($config_file_count+1))
            fi
            # 根据配置参数限制存储的文件数量,删除最早的文件
            if [ $config_file_count -ge $max_num_of_files ]; then
                rm -f "${real_path}"/"${file}"
            fi
        fi
        if [ ${#file} -gt 15 ] && [ ${file:0:$log_length} == "system_log-"$host_name ] && [ ${file##*.} == "log" ] && [ $log == "on" ]; then
            local file_time=`date +%s -r "${real_path}"/"${file}"`
            local now=`date +%s`
            let diff=$(($now-$file_time))
            if [ $diff -gt $(($retention*60*60*24)) ]; then
                rm -f "${real_path}"/"${file}"
            else
                log_file_count=$(($log_file_count+1))
            fi
            # 根据配置参数限制存储的文件数量,删除最早的文件
            if [ $log_file_count -ge $max_num_of_files ]; then
                rm -f "${real_path}"/"${file}"
            fi
        fi
    done

    if [ $config == "on" ]; then
        lua -e "require 'luci.controller.admin.firmware'.config_backup_tftp()"
        local time_now=`date +%Y-%m-%d-%H-%M-%S`
        local file_name="backup-"$host_name"-"$time_now".bin"
        cp -f $BACKUP_CRY "${real_path}"/"${file_name}"
        rm -f $BACKUP_TMP $BACKUP_CRY
    fi
    if [ $log == "on" ]; then
        local lang=`uci get locale.sysinfo.lang`
        local time_now=`date +%Y-%m-%d-%H-%M-%S`
        logger_read -w -l $lang > "${real_path}"/system_log-$host_name-$time_now.log
    fi
    sync
fi

