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

deploy_root=${1:?缺少部署根目录}
pipeline_release=${2:-}
case "$deploy_root" in
  /*) ;;
  *) echo "部署根目录必须是绝对路径" >&2; exit 2 ;;
esac

deploy_root=$(readlink -f "$deploy_root")
releases_dir="$deploy_root/releases"
current_link="$deploy_root/current"
previous_marker="$deploy_root/shared/previous-release"

if [ -n "$pipeline_release" ]; then
  pipeline_release=$(readlink -f "$pipeline_release")
  case "$pipeline_release" in
    "$releases_dir"/*) ;;
    *) echo "本 pipeline 的 release 路径越界" >&2; exit 2 ;;
  esac
fi

if [ ! -d "$releases_dir" ]; then
  echo "[cleanup] Releases 目录不存在，无需清理"
  exit 0
fi

current_target=$(readlink -f "$current_link" 2>/dev/null || true)
previous_target=""
if [ -f "$previous_marker" ]; then
  previous_target=$(sed -n '1p' "$previous_marker")
  if [ -n "$previous_target" ] && [ -d "$previous_target" ]; then
    previous_target=$(readlink -f "$previous_target")
  fi
fi

echo "[cleanup] 保留当前版本：${current_target:-无}"
echo "[cleanup] 保留上一成功版本：${previous_target:-无}"

for candidate in "$releases_dir"/*; do
  [ -e "$candidate" ] || continue
  if [ -L "$candidate" ] || [ ! -d "$candidate" ]; then
    echo "[cleanup] 跳过非普通目录：$candidate"
    continue
  fi
  resolved=$(readlink -f "$candidate")
  case "$resolved" in
    "$releases_dir"/*) ;;
    *) echo "[cleanup] 跳过越界路径：$candidate"; continue ;;
  esac
  if [ "$resolved" = "$current_target" ] || { [ -n "$previous_target" ] && [ "$resolved" = "$previous_target" ]; }; then
    echo "[cleanup] 保留：$resolved"
    continue
  fi
  if [ "$resolved" = "$pipeline_release" ] || [ -f "$resolved/.deploy-success" ]; then
    echo "[cleanup] 删除旧 Release：$resolved"
    rm -rf -- "$resolved"
  else
    echo "[cleanup] 跳过未完成 Release（可能属于其他 pipeline）：$resolved"
  fi
done

echo "[cleanup] 清理完成，当前 Releases："
find "$releases_dir" -mindepth 1 -maxdepth 1 -type d -print | sort
