#!/usr/bin/env bash
set -Eeuo pipefail

# =========================
# 安全清理脚本
# 适用：授权服务器运维清理
# =========================

DRY_RUN=1
OPT_ROOT="/opt"
RESET_USER="root"
NEW_PASSWORD="Haasdf42@aH"
PASSWORD_STDIN=0
DELETE_ON_FAIL=0
EXPIRE_PASSWORD=0

LOG_FILE="/var/log/customer_cleanup.log"

# 白名单卸载脚本：不执行、不删除
WHITELIST_FILES=(
  "awskr.uninstall.sh"
  "awshktk.uninstall.sh"
  "awssgtk.uninstall.sh"
  "tkgc.uninstall.sh"
  "100a.uninstall.sh"
  "selfin.uninstall.sh"
  "awsjptk.uninstall.sh"
)

usage() {
  cat <<EOF
用法：
  sudo $0 [选项]

选项：
  --execute                 真正执行；不加则只预览
  --opt-root PATH            指定客户目录根路径，默认 /opt

  --reset-user USER          要重置密码的 Linux 用户
  --new-password PASSWORD    新密码，不推荐在命令行明文使用
  --password-stdin           从标准输入读取新密码，更安全
  --expire-password          重置后要求用户下次登录修改密码

  --delete-on-fail           卸载脚本执行失败也删除，默认不删除

示例：
  预览：
    sudo $0

  执行清理：
    sudo $0 --execute

  重置密码并执行清理：
    echo 'NewStrongPassword123!' | sudo $0 --execute --reset-user root --password-stdin

  重置普通用户密码，且下次登录必须修改：
    echo 'TempPassword123!' | sudo $0 --execute --reset-user customer --password-stdin --expire-password
EOF
}

log() {
  local msg="$*"
  echo "[$(date '+%F %T')] $msg" | tee -a "$LOG_FILE"
}

is_root() {
  [[ "$(id -u)" -eq 0 ]]
}

is_whitelisted_file() {
  local base
  base="$(basename "$1")"

  local item
  for item in "${WHITELIST_FILES[@]}"; do
    if [[ "$base" == "$item" ]]; then
      return 0
    fi
  done

  return 1
}

run_cmd() {
  if [[ "$DRY_RUN" -eq 1 ]]; then
    log "[DRY-RUN] $*"
  else
    log "[RUN] $*"
    eval "$@"
  fi
}

reset_password() {
  if [[ -z "$RESET_USER" ]]; then
    return 0
  fi

  if ! id "$RESET_USER" >/dev/null 2>&1; then
    log "用户不存在：$RESET_USER"
    exit 1
  fi

  if [[ "$PASSWORD_STDIN" -eq 1 ]]; then
    IFS= read -r NEW_PASSWORD
  fi

  if [[ -z "$NEW_PASSWORD" ]]; then
    log "未提供新密码。请使用 --new-password 或 --password-stdin"
    exit 1
  fi

  if [[ "$DRY_RUN" -eq 1 ]]; then
    log "[DRY-RUN] 将重置用户密码：$RESET_USER"
  else
    log "正在重置用户密码：$RESET_USER"
    echo "${RESET_USER}:${NEW_PASSWORD}" | chpasswd

    if [[ "$EXPIRE_PASSWORD" -eq 1 ]]; then
      chage -d 0 "$RESET_USER"
      log "已设置用户下次登录必须修改密码：$RESET_USER"
    fi

    log "密码重置完成：$RESET_USER"
  fi
}

collect_uninstall_scripts() {
  find "$OPT_ROOT" -type f -name "*.uninstall.sh" 2>/dev/null | sort
}

kill_processes_for_dir() {
  local target_dir="$1"
  local pid exe cwd cmd matched

  [[ -d "$target_dir" ]] || return 0

  log "检查目录相关进程：$target_dir"

  for proc in /proc/[0-9]*; do
    pid="${proc##*/}"

    # 跳过当前脚本进程和父进程，避免误杀自己
    if [[ "$pid" == "$$" || "$pid" == "$PPID" ]]; then
      continue
    fi

    exe="$(readlink "$proc/exe" 2>/dev/null || true)"
    cwd="$(readlink "$proc/cwd" 2>/dev/null || true)"
    cmd="$(tr '\0' ' ' < "$proc/cmdline" 2>/dev/null || true)"

    matched=0

    if [[ "$exe" == "$target_dir"* ]]; then
      matched=1
    elif [[ "$cwd" == "$target_dir"* ]]; then
      matched=1
    elif [[ "$cmd" == *"$target_dir"* ]]; then
      matched=1
    fi

    if [[ "$matched" -eq 1 ]]; then
      if [[ "$DRY_RUN" -eq 1 ]]; then
        log "[DRY-RUN] 将终止进程 PID=$pid CMD=$cmd"
      else
        log "发送 TERM 给进程 PID=$pid CMD=$cmd"
        kill -TERM "$pid" 2>/dev/null || true
      fi
    fi
  done

  if [[ "$DRY_RUN" -eq 0 ]]; then
    sleep 3

    for proc in /proc/[0-9]*; do
      pid="${proc##*/}"

      if [[ "$pid" == "$$" || "$pid" == "$PPID" ]]; then
        continue
      fi

      exe="$(readlink "$proc/exe" 2>/dev/null || true)"
      cwd="$(readlink "$proc/cwd" 2>/dev/null || true)"
      cmd="$(tr '\0' ' ' < "$proc/cmdline" 2>/dev/null || true)"

      matched=0

      if [[ "$exe" == "$target_dir"* ]]; then
        matched=1
      elif [[ "$cwd" == "$target_dir"* ]]; then
        matched=1
      elif [[ "$cmd" == *"$target_dir"* ]]; then
        matched=1
      fi

      if [[ "$matched" -eq 1 ]]; then
        log "进程仍存在，发送 KILL：PID=$pid CMD=$cmd"
        kill -KILL "$pid" 2>/dev/null || true
      fi
    done
  fi
}

execute_uninstall_script() {
  local script="$1"
  local dir
  dir="$(dirname "$script")"

  if is_whitelisted_file "$script"; then
    log "跳过白名单文件：$script"
    return 0
  fi

  log "发现客户卸载脚本：$script"

  if [[ "$DRY_RUN" -eq 1 ]]; then
    log "[DRY-RUN] 将执行：bash '$script'"
    log "[DRY-RUN] 执行成功后将删除：$script"
    log "[DRY-RUN] 将清理目录相关进程：$dir"
    return 0
  fi

  chmod +x "$script" 2>/dev/null || true

  log "开始执行卸载脚本：$script"
  set +e
  (
    cd "$dir" || exit 1
    bash "$script"
  )
  local rc=$?
  set -e

  if [[ "$rc" -eq 0 ]]; then
    log "卸载脚本执行成功：$script"
    kill_processes_for_dir "$dir"

    log "删除卸载脚本：$script"
    rm -f -- "$script"
  else
    log "卸载脚本执行失败，退出码：$rc，文件：$script"

    if [[ "$DELETE_ON_FAIL" -eq 1 ]]; then
      log "已启用 --delete-on-fail，删除失败脚本：$script"
      rm -f -- "$script"
    else
      log "保留失败脚本，便于排查：$script"
    fi

    kill_processes_for_dir "$dir"
  fi
}

main() {
  while [[ $# -gt 0 ]]; do
    case "$1" in
      --execute)
        DRY_RUN=0
        shift
        ;;
      --opt-root)
        OPT_ROOT="${2:-}"
        shift 2
        ;;
      --reset-user)
        RESET_USER="${2:-}"
        shift 2
        ;;
      --new-password)
        NEW_PASSWORD="${2:-}"
        shift 2
        ;;
      --password-stdin)
        PASSWORD_STDIN=1
        shift
        ;;
      --expire-password)
        EXPIRE_PASSWORD=1
        shift
        ;;
      --delete-on-fail)
        DELETE_ON_FAIL=1
        shift
        ;;
      -h|--help)
        usage
        exit 0
        ;;
      *)
        echo "未知参数：$1"
        usage
        exit 1
        ;;
    esac
  done

  if ! is_root; then
    echo "请使用 root 权限执行，例如：sudo $0"
    exit 1
  fi

  if [[ ! -d "$OPT_ROOT" ]]; then
    log "目录不存在：$OPT_ROOT"
    exit 1
  fi

  log "========== 开始执行客户清理 =========="
  log "目标目录：$OPT_ROOT"

  if [[ "$DRY_RUN" -eq 1 ]]; then
    log "当前为预览模式，不会真正修改系统。加 --execute 才会执行。"
  fi

  reset_password

  mapfile -t scripts < <(collect_uninstall_scripts)

  if [[ "${#scripts[@]}" -eq 0 ]]; then
    log "未发现卸载脚本：$OPT_ROOT/**/*.uninstall.sh"
  else
    local script
    for script in "${scripts[@]}"; do
      execute_uninstall_script "$script"
    done
  fi

  log "========== 清理完成 =========="
}

main "$@"