#!/usr/bin/env bash
# safe_rm: 交互式 rm 替代；普通路径归档，指定排除路径直接真实删除
set -euo pipefail

TRASH_BASE="${TRASH_BASE:-$HOME/.trash}"
TRASH_ARCHIVE_BASE="${TRASH_ARCHIVE_BASE:-$HOME/.trash_archive}"
SAFE_RM_DIRECT_PATHS_RAW="${SAFE_RM_DIRECT_PATHS:-$TRASH_BASE:$TRASH_ARCHIVE_BASE}"
TS="$(date +%Y%m%d_%H%M%S)"
mkdir -p "$TRASH_BASE" "$TRASH_ARCHIVE_BASE"

full_cmd="rm $*"
paths=()
danger=false

auto_realpaths=()

echo_line() {
  printf '%s\n' "$*"
}

canonicalize() {
  python3 - "$1" <<'PY2'
import os, sys
print(os.path.realpath(sys.argv[1]))
PY2
}

for arg in "$@"; do
  case "$arg" in
    -r|-R|-f|-rf|-fr)
      danger=true
      ;;
    --)
      shift
      for rest in "$@"; do paths+=("$rest"); done
      break
      ;;
    -*)
      ;;
    *)
      paths+=("$arg")
      ;;
  esac
done

if [ "${#paths[@]}" -eq 0 ]; then
  echo "safe_rm: no paths given" >&2
  exit 1
fi

trash_real="$(canonicalize "$TRASH_BASE")"
archive_real="$(canonicalize "$TRASH_ARCHIVE_BASE")"

IFS=':' read -r -a direct_roots <<< "$SAFE_RM_DIRECT_PATHS_RAW"
for root in "${direct_roots[@]}"; do
  [ -n "$root" ] || continue
  if [ -e "$root" ]; then
    auto_realpaths+=("$(canonicalize "$root")")
  else
    case "$root" in
      ~/*) auto_realpaths+=("$HOME/${root#~/}") ;;
      *) auto_realpaths+=("$root") ;;
    esac
  fi
done

is_direct_delete_target() {
  local target_real="$1"
  local direct_root
  for direct_root in "${auto_realpaths[@]}"; do
    case "$target_real" in
      "$direct_root"|"$direct_root"/*)
        return 0
        ;;
    esac
  done
  return 1
}

echo "=========================================="
echo "  ⚠️  危险操作检测"
echo "=========================================="
echo

echo "命令: $full_cmd"
if [ "$danger" = true ]; then
  echo "风险: 使用 -rf 强制删除 ${#paths[@]} 个文件/目录"
else
  echo "风险: 删除 ${#paths[@]} 个文件/目录"
fi
echo

echo "⚠️  警告：此操作可能删除多个文件"
echo
echo "要删除的文件/目录（共 ${#paths[@]} 个）:"
for target in "${paths[@]}"; do
  echo "  - $target"
done
echo

if [ "${#auto_realpaths[@]}" -gt 0 ]; then
  echo "直接真实删除白名单:"
  for direct_root in "${auto_realpaths[@]}"; do
    echo "  - $direct_root"
  done
  echo
fi

read -r -p "请输入 yes 以继续，或按 Ctrl+C 取消： " answer
if [ "$answer" != "yes" ]; then
  echo "safe_rm: 已取消" >&2
  exit 1
fi

for target in "${paths[@]}"; do
  if [ ! -e "$target" ]; then
    echo "safe_rm: not found: $target" >&2
    continue
  fi

  target_real="$(canonicalize "$target")"

  if is_direct_delete_target "$target_real"; then
    /usr/bin/rm -rf -- "$target"
    echo "safe_rm: direct-deleted $target" >&2
    continue
  fi

  base_name="$(basename -- "$target")"
  dest_root="$TRASH_BASE"

  case "$target_real" in
    "$trash_real"|"$trash_real"/*)
      dest_root="$TRASH_ARCHIVE_BASE"
      ;;
    "$archive_real"|"$archive_real"/*)
      dest_root="${TRASH_ARCHIVE_BASE}_overflow"
      mkdir -p "$dest_root"
      ;;
  esac

  dest="${dest_root}/${base_name}_$TS"
  if [ -e "$dest" ]; then
    dest="${dest}_$$"
  fi

  mv -- "$target" "$dest"
  echo "safe_rm: moved $target -> $dest" >&2
done
