#!/bin/bash
# SkillHub自动同步脚本：检测./skills下的技能变更，自动推送到Vala SkillHub
# 遵循use_vala_skillhub.vala技能规范实现
WORKDIR="/root/.openclaw/workspace-xiaoban"
cd "${WORKDIR}" || exit 1
source ./.vala_skillhub_config
HASH_FILE=./.vala_skill_hashes
touch "${HASH_FILE}"
mkdir -p ./tmp/skill_push
SYNC_COUNT=0
SKIP_COUNT=0
# 计算技能目录哈希函数
compute_skill_hash() {
  local skill_dir="$1"
  (cd "${skill_dir}" && find . -type f -not -path '*/\.*' | LC_ALL=C sort | while read f; do echo "FILE:$f"; cat "$f"; done | sha256sum | awk '{print $1}')
}
for skill_dir in ./skills/*/; do
    skill_name=$(basename "${skill_dir}")
    # 跳过use_vala_skillhub自身（兼容带和不带.vala后缀的命名）
    if [[ "${skill_name}" == "use_vala_skillhub"* ]]; then
        continue
    fi
    # 计算当前目录哈希（遵循规范哈希算法）
    current_hash=$(compute_skill_hash "${skill_dir}")
    stored_hash=$(grep "^${skill_name} " "${HASH_FILE}" | awk '{print $2}')
    if [ "${current_hash}" = "${stored_hash}" ]; then
        SKIP_COUNT=$((SKIP_COUNT + 1))
        continue
    fi
    SYNC_COUNT=$((SYNC_COUNT + 1))
    echo "[sync] ${skill_name} — 检测到变更，开始推送..."
    repo_name="${skill_name}.${SOURCE_NAME}"
    # 检查远程仓库是否存在
    http_code=$(curl -s -o /dev/null -w "%{http_code}" \
        "${GITEA_URL}/api/v1/repos/${GITEA_OWNER}/${repo_name}" \
        -H "Authorization: token ${GITEA_TOKEN}")
    # 不存在则创建
    if [ "${http_code}" = "404" ]; then
        desc=""
        if [ -f "${skill_dir}/skill.json" ]; then
            desc=$(cat "${skill_dir}/skill.json" | grep '"description"' | head -1 | sed 's/.*"description"[[:space:]]*:[[:space:]]*"\(.*\)".*/\1/')
        fi
        curl -s -X POST "${GITEA_URL}/api/v1/orgs/${GITEA_OWNER}/repos" \
            -H "Authorization: token ${GITEA_TOKEN}" \
            -H "Content-Type: application/json" \
            -d '{"name": "'"${repo_name}"'", "private": false, "description": "'"${desc}"'", "auto_init": false}' >/dev/null 2>&1
    fi
    # 复制到临时目录推送
    rm -rf ./tmp/skill_push/${repo_name}
    mkdir -p ./tmp/skill_push/${repo_name}
    cp -r ${skill_dir}* ./tmp/skill_push/${repo_name}/
    cp -r ${skill_dir}.[!.]* ./tmp/skill_push/${repo_name}/ 2>/dev/null || true
    cd ./tmp/skill_push/${repo_name} || exit 1
    git init >/dev/null 2>&1
    git checkout -b main >/dev/null 2>&1
    git add -A >/dev/null 2>&1
    git commit -m "auto-sync: ${skill_name} $(date +%Y-%m-%d_%H:%M)" >/dev/null 2>&1
    git remote add origin "https://oauth2:${GITEA_TOKEN}@${GITEA_URL#https://}/${GITEA_OWNER}/${repo_name}.git"
    git push -u origin main --force >/dev/null 2>&1
    cd "${WORKDIR}" || exit 1
    rm -rf ./tmp/skill_push/${repo_name}
    # 更新哈希记录
    grep -v "^${skill_name} " "${HASH_FILE}" > "${HASH_FILE}.tmp" || true
    echo "${skill_name} ${current_hash}" >> "${HASH_FILE}.tmp"
    mv "${HASH_FILE}.tmp" "${HASH_FILE}"
    echo "[done] ${skill_name} — 推送完成"
done
echo "同步完成：推送 ${SYNC_COUNT} 个技能，跳过 ${SKIP_COUNT} 个无变更技能"
