#!/bin/bash
# 飞书多维表格Bot操作脚本
ACTION="$1"
APP_TOKEN="$2"
TABLE_ID="$3"
RECORD_ID="$4"
FIELDS="$5"
PAGE_SIZE="${5:-50}"
CRED_FILE="/root/.openclaw/credentials/xiaoyan/config.json"
APP_ID=$(jq -r '.apps[0].appId' "$CRED_FILE")
APP_SECRET=$(jq -r '.apps[0].appSecret' "$CRED_FILE")
# 获取tenant_access_token
get_token() {
  TOKEN=$(curl -s -X POST "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal" \
    -H "Content-Type: application/json" \
    -d "{\"app_id\":\"$APP_ID\",\"app_secret\":\"$APP_SECRET\"}" \
    | jq -r '.tenant_access_token')
  echo "$TOKEN"
}
TOKEN=$(get_token)
case "$ACTION" in
  list_tables)
    if [ -z "$APP_TOKEN" ]; then
      echo "参数错误：请传入app_token"
      exit 1
    fi
    curl -s -X GET "https://open.feishu.cn/open-apis/bitable/v1/apps/$APP_TOKEN/tables" \
      -H "Authorization: Bearer $TOKEN"
    ;;
  list_records)
    if [ -z "$APP_TOKEN" ] || [ -z "$TABLE_ID" ]; then
      echo "参数错误：请传入app_token和table_id"
      exit 1
    fi
    curl -s -X GET "https://open.feishu.cn/open-apis/bitable/v1/apps/$APP_TOKEN/tables/$TABLE_ID/records?page_size=$PAGE_SIZE" \
      -H "Authorization: Bearer $TOKEN"
    ;;
  create_record)
    if [ -z "$APP_TOKEN" ] || [ -z "$TABLE_ID" ] || [ -z "$4" ]; then
      echo "参数错误：请传入app_token、table_id和fields JSON"
      exit 1
    fi
    FIELDS="$4"
    curl -s -X POST "https://open.feishu.cn/open-apis/bitable/v1/apps/$APP_TOKEN/tables/$TABLE_ID/records" \
      -H "Authorization: Bearer $TOKEN" \
      -H "Content-Type: application/json" \
      -d "{\"fields\":$FIELDS}"
    ;;
  update_record)
    if [ -z "$APP_TOKEN" ] || [ -z "$TABLE_ID" ] || [ -z "$RECORD_ID" ] || [ -z "$5" ]; then
      echo "参数错误：请传入app_token、table_id、record_id和fields JSON"
      exit 1
    fi
    FIELDS="$5"
    curl -s -X PUT "https://open.feishu.cn/open-apis/bitable/v1/apps/$APP_TOKEN/tables/$TABLE_ID/records/$RECORD_ID" \
      -H "Authorization: Bearer $TOKEN" \
      -H "Content-Type: application/json" \
      -d "{\"fields\":$FIELDS}"
    ;;
  delete_record)
    if [ -z "$APP_TOKEN" ] || [ -z "$TABLE_ID" ] || [ -z "$RECORD_ID" ]; then
      echo "参数错误：请传入app_token、table_id和record_id"
      exit 1
    fi
    curl -s -X DELETE "https://open.feishu.cn/open-apis/bitable/v1/apps/$APP_TOKEN/tables/$TABLE_ID/records/$RECORD_ID" \
      -H "Authorization: Bearer $TOKEN"
    ;;
  *)
    echo "支持的操作：list_tables / list_records / create_record / update_record / delete_record"
    exit 1
    ;;
esac