#!/bin/bash
set -eu
case "${wizard_data_action:-keep}" in
    keep) exit 0 ;;
    license|delete) ;;
    *) echo '未知的数据处理选项，未删除数据' >&2; exit 1 ;;
esac
DATA_DIR="${TRIM_DATA_SHARE_PATHS:-}"
DATA_DIR="${DATA_DIR%%:*}"
DATA_DIR="${DATA_DIR:-${TRIM_PKGVAR:?}/data}"
case "$DATA_DIR" in /*) ;; *) echo '应用数据目录必须是绝对路径' >&2; exit 1 ;; esac
[ ! -L "$DATA_DIR" ] || { echo '拒绝清理符号链接数据目录' >&2; exit 1; }
[ -d "$DATA_DIR" ] || exit 0
cd -P -- "$DATA_DIR"
[ "$PWD" != / ] || exit 1
# fnOS stops the service before uninstall. Also refuse a concurrent lifecycle
# command or CLI migration; keep the same lock inode until cleanup completes.
command -v flock >/dev/null || { echo '安全清理需要 flock，未删除数据' >&2; exit 1; }
mkdir -p "${TRIM_PKGVAR:?}"
[ ! -L "$TRIM_PKGVAR/lifecycle.lock" ] && [ ! -L .instance.lock ] || exit 1
exec 9>>"$TRIM_PKGVAR/lifecycle.lock"
flock -w 45 9
# Clear per-user platform sessions inside the encrypted license DB before
# removing local users. The CLI takes the data lock; the later shell lock
# refuses deletion if another service/CLI starts between these two stages.
if [ -e licenses.db ] || [ -L licenses.db ] || [ -e docker-licenses.db ] || [ -L docker-licenses.db ]; then
    SERVER="${TRIM_APPDEST:?}/server/leelaa-drama"
    [ -x "$SERVER" ] || { echo '授权库账号清理程序不可用，未删除业务数据' >&2; exit 1; }
    DRAMA_MODE=fnos DRAMA_DEV=0 DRAMA_DATA_DIR="$PWD" "$SERVER" forget-license-accounts --service-stopped 9>&-
fi
exec 8>>.instance.lock
flock -n 8 || { echo '应用或迁移仍在使用数据，未删除数据' >&2; exit 1; }

# Delete only known business artifacts. Never remove the data root, original
# videos, license databases, their WAL/SHM, device keys or authorization trust.
for database in drama.db users.db; do
    for suffix in '' .sqlcipher-plaintext-backup .sqlcipher-migrating .sqlcipher-failed \
        .sqlcipher-legacy-key-backup .sqlcipher-key-migrating .sqlcipher-key-failed; do
        rm -f -- "$database$suffix" "$database$suffix-wal" "$database$suffix-shm" "$database$suffix-journal"
    done
done
rm -f -- catalog.json catalog.tmp libraries.json libraries.tmp metadata.json metadata.tmp \
    bootstrap-admin.txt migration-report.json migration-pending.json
rm -rf -- cache playback-work posters .migration-*
rm -f -- "$TRIM_PKGVAR/drama.log" "$TRIM_PKGVAR/drama.log.1" "$TRIM_PKGVAR/drama.pid"
rm -f -- "$TRIM_PKGVAR/app-port"
if [ -d "$TRIM_PKGVAR/tls" ] && [ ! -L "$TRIM_PKGVAR/tls" ]; then
    rm -rf -- "$TRIM_PKGVAR/tls"
fi
if [ "${wizard_data_action:-keep}" = delete ]; then
    # 彻底清除授权时移除本地授权数据库与密钥残留；外部信任根和原始媒体不在卸载范围。
    for database in licenses.db docker-licenses.db; do
        for suffix in '' .sqlcipher-plaintext-backup .sqlcipher-migrating .sqlcipher-failed \
            .sqlcipher-legacy-key-backup .sqlcipher-key-migrating .sqlcipher-key-failed; do
            rm -f -- "$database$suffix" "$database$suffix-wal" "$database$suffix-shm" "$database$suffix-journal"
        done
    done
fi
exit 0
