#!/bin/bash

# 切换到脚本所在目录读取data.txt
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

# TXT 文件路径
txt_file_path="$SCRIPT_DIR/data.txt"

# CLI_client 执行目录
cli_dir="/opt/preinstall/b01odm/files"

# 基础命令模板
base_command="./CLI_client appsig_bin add"

# 初始 ruleid
ruleid=100000

# 基础 JSON 模板参数
appid=1654
name="边缘缓存服务"
stype="diport"
prio=4
offest=0

# 检查文件是否存在
if [ ! -f "$txt_file_path" ]; then
    echo "Error: The file '$txt_file_path' does not exist."
    exit 1
fi

# 检查CLI目录是否存在
if [ ! -d "$cli_dir" ]; then
    echo "Error: The directory '$cli_dir' does not exist."
    exit 1
fi

# 读取文件并处理每一行
while IFS= read -r line || [ -n "$line" ]; do
    # 去掉首尾空格
    value=$(echo "$line" | xargs)
    
    # 确保 value 不为空
    if [ -n "$value" ]; then
        # 递增 ruleid
        ruleid=$((ruleid + 1))
        
        # 构建 JSON 字符串
        json_str="{\"ruleid\":$ruleid,\"appid\":$appid,\"name\":\"$name\",\"stype\":\"$stype\",\"value\":\"$value\",\"prio\":$prio,\"offest\":$offest}"
        
        # 生成完整的命令
        command="$base_command '$json_str'"
        
        # 输出将要执行的命令
        echo "Executing: $command"
        
        # 切换到CLI目录并执行命令
        (cd "$cli_dir" && eval "$command")
        
        # 自动延迟1秒后继续下一条命令
        sleep 1
        echo
    fi
done < "$txt_file_path" 