#!/bin/bash
# SafeSight 初始资产导入脚本
# 将 edge 项目 configs 目录下的模板/场景/覆盖层导入管理端数据库
# 用法: sudo bash import-assets.sh

set -e

DB="/opt/safesightd/data/app.db"
CONFIGS_DIR="${1:-/tmp/configs}"

if [ ! -f "$DB" ]; then
  echo "错误: 数据库文件不存在: $DB"
  exit 1
fi

if [ ! -d "$CONFIGS_DIR/templates" ]; then
  echo "错误: configs 目录不存在: $CONFIGS_DIR"
  echo "请先把 edge 项目的 configs/templates configs/profiles configs/overlays 复制到 $CONFIGS_DIR"
  exit 1
fi

NOW=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
T=0; P=0; O=0

import_json() {
  local table="$1" name="$2" file="$3"
  # 使用 base64 编码绕过 JSON 中的特殊字符问题
  local b64=$(cat "$file" | base64 -w0)
  sqlite3 "$DB" "INSERT OR IGNORE INTO ${table} (name, description, body_json, created_at, updated_at)
    VALUES ('${name}', '', CAST(X'$(echo -n "$b64" | base64 -d | xxd -p -c0 | tr -d '\n')' AS TEXT), '${NOW}', '${NOW}');"
}

echo "========== SafeSight 资产导入 =========="
echo "数据库: $DB"
echo "配置源: $CONFIGS_DIR"
echo ""

# 导入模板
for f in "$CONFIGS_DIR/templates"/*.json; do
  [ -f "$f" ] || continue
  name=$(basename "$f" .json)
  import_json "templates" "$name" "$f"
  echo "  ✓ 模板: $name"
  ((T++))
done

# 导入场景
for f in "$CONFIGS_DIR/profiles"/*.json; do
  [ -f "$f" ] || continue
  name=$(basename "$f" .json)
  import_json "profiles" "$name" "$f"
  echo "  ✓ 场景: $name"
  ((P++))
done

# 导入覆盖层
for f in "$CONFIGS_DIR/overlays"/*.json; do
  [ -f "$f" ] || continue
  name=$(basename "$f" .json)
  import_json "overlays" "$name" "$f"
  echo "  ✓ 覆盖层: $name"
  ((O++))
done

echo ""
echo "========== 导入完成 =========="
echo "模板: $T  场景: $P  覆盖层: $O"
echo ""
echo "请执行: sudo systemctl restart safesightd"
