#!/bin/bash
# uninstall_callback：卸载清理**之后**执行。
#
# 语义：
#   - 默认**保留**全部数据
#   - 仅当 wizard_keep_data 被显式设为假值时才清理
#   - 失败安全：向导变量缺失、无法识别、环境异常一律按「保留」处理
#
# 飞牛的「手动安装」会先执行卸载回调再走安装流程；默认删数据等于每次重装都丢令牌。
set -uo pipefail

TP_HOOK=uninstall_callback
SELF_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=lib.sh
. "$SELF_DIR/lib.sh"

tp_dump_env uninstall_callback

keep_raw="${wizard_keep_data:-}"

if ! tp_is_falsy "$keep_raw"; then
    tp_log uninstall_callback "卸载清理：wizard_keep_data=[$keep_raw] → 保留数据"
    exit 0
fi

tp_log uninstall_callback "卸载清理：wizard_keep_data=[$keep_raw] → 用户明确选择删除数据"

data="${TRIM_PKGVAR:-}"
if [ -z "$data" ]; then
    tp_log uninstall_callback "TRIM_PKGVAR 为空，无从删除，按保留处理"
    exit 0
fi
if [ ! -d "$data" ]; then
    tp_log uninstall_callback "数据目录不存在，无需删除"
    exit 0
fi
case "$data" in
    /|.|..|/*) ;;
    *) tp_log uninstall_callback "数据目录不是绝对路径（$data），按保留处理"; exit 0 ;;
esac
if [ "$data" = "/" ] || [ "$data" = "." ] || [ "$data" = ".." ]; then
    tp_log uninstall_callback "拒绝在危险路径（$data）执行删除，按保留处理"
    exit 0
fi

# 只删自己创建的内容，不删数据目录本身（目录归平台管）。
for item in logs backup tmp totpilot.db totpilot.db-wal totpilot.db-shm \
            totpilot.db.rollback totpilot.db.restore.tmp master.key master.key.rollback \
            restore.journal hub.token .last-version app.pid lifecycle.log; do
    rm -rf "$data/$item" 2>/dev/null || true
done

tp_log uninstall_callback "数据清理完成"
exit 0
