#!/usr/bin/env bash
# datahub 卸载脚本
#
# 默认行为：停服务 + 移除 Quadlet + 删 secrets，保留数据目录和镜像
#
# 用法：bash uninstall.sh [选项]
#   --purge-images   同时删除 3 个本地镜像
#   --purge-data     同时删除 /var/container/data/datahub/ 数据目录（危险）
#   -y, --yes        不询问确认（用于自动化）

set -euo pipefail

B='\033[34m'; G='\033[32m'; Y='\033[33m'; R='\033[31m'; N='\033[0m'
ok()   { echo -e "${G}[OK]${N} $*"; }
warn() { echo -e "${Y}[!]${N} $*"; }

PURGE_IMAGES=false
PURGE_DATA=false
ASSUME_YES=false

for arg in "$@"; do
    case "$arg" in
        --purge-images) PURGE_IMAGES=true ;;
        --purge-data)   PURGE_DATA=true ;;
        -y|--yes)       ASSUME_YES=true ;;
        -h|--help)
            sed -n '2,11p' "$0"
            exit 0
            ;;
        *) echo "未知参数: $arg" >&2; exit 1 ;;
    esac
done

QUADLET_DIR="$HOME/.config/containers/systemd"
DATA_DIR=/var/container/data/datahub
SERVICES=(datahub-frontend datahub-backend datahub-rabbitmq datahub-postgres)
QUADLET_FILES=(
    datahub-frontend.container
    datahub-backend.container
    datahub-rabbitmq.container
    datahub-postgres.container
    datahub.network
)
SECRETS=(datahub-pg-password datahub-rabbitmq-password datahub-jwt-secret datahub-tools-token)
IMAGES=(localhost/datahub-postgres:latest localhost/datahub-backend:latest localhost/datahub-frontend:latest)

echo -e "${B}=== datahub 卸载脚本 ===${N}"
echo
echo "将执行以下操作："
echo "  - 停止 4 个 systemd 服务"
echo "  - 移除 ${#QUADLET_FILES[@]} 个 Quadlet 单元"
echo "  - 删除 ${#SECRETS[@]} 个 podman secrets"
echo -n "  - 镜像: "
[ "$PURGE_IMAGES" = true ] && echo -e "${R}删除${N}" || echo "保留"
echo -n "  - 数据目录 $DATA_DIR: "
[ "$PURGE_DATA" = true ] && echo -e "${R}删除（数据将丢失）${N}" || echo "保留"
echo

if [ "$ASSUME_YES" = false ]; then
    read -rp "确认继续？(y/N): " ans
    [[ "${ans,,}" == "y" ]] || { echo "已取消"; exit 0; }
fi

# 1. 停服务
echo -e "\n${B}-> 停止服务${N}"
for svc in "${SERVICES[@]}"; do
    if systemctl --user is-active --quiet "$svc.service" 2>/dev/null; then
        systemctl --user stop "$svc.service" || true
        echo "  停止 $svc"
    fi
done

# 2. 移除 Quadlet 文件
echo -e "\n${B}-> 移除 Quadlet 单元${N}"
for f in "${QUADLET_FILES[@]}"; do
    if [ -f "$QUADLET_DIR/$f" ]; then
        rm -f "$QUADLET_DIR/$f"
        echo "  删除 $f"
    fi
done
systemctl --user daemon-reload

# 3. 清理残留容器（保险起见）
for c in datahub-postgres datahub-rabbitmq datahub-backend datahub-frontend; do
    if podman container exists "$c" 2>/dev/null; then
        podman rm -f "$c" >/dev/null
        echo "  删除残留容器 $c"
    fi
done

# 4. 删 secrets
echo -e "\n${B}-> 删除 secrets${N}"
for s in "${SECRETS[@]}"; do
    if podman secret exists "$s" 2>/dev/null; then
        podman secret rm "$s" >/dev/null
        echo "  删除 $s"
    fi
done

# 5. 删镜像（可选）
if [ "$PURGE_IMAGES" = true ]; then
    echo -e "\n${B}-> 删除镜像${N}"
    for img in "${IMAGES[@]}"; do
        if podman image exists "$img" 2>/dev/null; then
            podman rmi "$img" >/dev/null && echo "  删除 $img"
        fi
    done
fi

# 6. 删数据目录（危险，双重确认）
if [ "$PURGE_DATA" = true ]; then
    echo -e "\n${R}-> 删除数据目录${N}"
    if [ "$ASSUME_YES" = false ]; then
        echo -e "${R}警告：将永久删除 $DATA_DIR 及全部数据${N}"
        read -rp "请输入完整的 'yes' 以确认: " ans
        if [ "$ans" != "yes" ]; then
            echo "数据目录保留"
            ASSUME_YES=skip_data
        fi
    fi
    if [ "$ASSUME_YES" != "skip_data" ]; then
        sudo rm -rf "$DATA_DIR"
        echo "  数据目录已删除"
    fi
fi

echo
ok "卸载完成"
[ "$PURGE_DATA" = false ] && warn "数据保留在 $DATA_DIR（重新部署可直接恢复）"
[ "$PURGE_IMAGES" = false ] && warn "镜像保留（podman images | grep datahub 可见）"
