#!/bin/bash

# Momentry 系统关机准备脚本
# 优雅地关闭所有服务，准备完全关机

set -e

echo "================================================"
echo "Momentry 系统关机准备"
echo "时间: $(date)"
echo "================================================"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log() {
	echo -e "${BLUE}[$(date '+%Y-%m-%d %H:%M:%S')]${NC} $1"
}

success() {
	echo -e "${GREEN}✓${NC} $1"
}

warning() {
	echo -e "${YELLOW}⚠${NC} $1"
}

error() {
	echo -e "${RED}✗${NC} $1"
}

# 检查是否以正确用户运行
if [ "$(whoami)" != "accusys" ]; then
	error "请以 'accusys' 用户运行此脚本"
	exit 1
fi

# 步骤1: 停止监控服务
log "步骤1: 停止监控服务..."
if pgrep -f "node_monitor.sh" >/dev/null; then
	pkill -f "node_monitor.sh"
	sleep 2
	success "监控服务已停止"
else
	warning "监控服务未运行"
fi

# 步骤2: 停止 Momentry 服务器
log "步骤2: 停止 Momentry 服务器..."
if pgrep -f "momentry server" >/dev/null; then
	pkill -TERM -f "momentry server"
	sleep 5
	if pgrep -f "momentry server" >/dev/null; then
		warning "Momentry 服务器仍在运行，发送 SIGKILL..."
		pkill -KILL -f "momentry server"
	fi
	success "Momentry 服务器已停止"
else
	warning "Momentry 服务器未运行"
fi

# 步骤3: 停止 MCP 服务器
log "步骤3: 停止 MCP 服务器..."
mcp_servers=(
	"mcp-server-redis"
	"mcp-server-postgres"
	"mcp-server-filesystem"
	"mcp-server-qdrant"
	"mongodb-mcp-server"
	"gitea-mcp-server"
)

for server in "${mcp_servers[@]}"; do
	if pgrep -f "$server" >/dev/null; then
		pkill -f "$server"
		sleep 1
		success "MCP 服务器 $server 已停止"
	fi
done

# 步骤4: 停止 PHP-FPM
log "步骤4: 停止 PHP-FPM..."
if pgrep -f "php-fpm" >/dev/null; then
	pkill -TERM php-fpm
	sleep 3
	success "PHP-FPM 已停止"
else
	warning "PHP-FPM 未运行"
fi

# 步骤5: 停止 Caddy
log "步骤5: 停止 Caddy..."
if pgrep -f "caddy" >/dev/null; then
	pkill -TERM caddy
	sleep 2
	success "Caddy 已停止"
else
	warning "Caddy 未运行"
fi

# 步骤6: 停止 Gitea
log "步骤6: 停止 Gitea..."
if pgrep -f "gitea web" >/dev/null; then
	pkill -TERM -f "gitea web"
	sleep 3
	success "Gitea 已停止"
else
	warning "Gitea 未运行"
fi

# 步骤7: 停止 SFTPGo
log "步骤7: 停止 SFTPGo..."
if pgrep -f "sftpgo serve" >/dev/null; then
	pkill -TERM -f "sftpgo serve"
	sleep 2
	success "SFTPGo 已停止"
else
	warning "SFTPGo 未运行"
fi

# 步骤8: 停止 n8n (如果运行)
log "步骤8: 停止 n8n..."
if pgrep -f "n8n" >/dev/null; then
	pkill -TERM -f "n8n"
	sleep 2
	success "n8n 已停止"
else
	warning "n8n 未运行"
fi

# 步骤9: 停止 Ollama
log "步骤9: 停止 Ollama..."
if pgrep -f "ollama" >/dev/null; then
	pkill -TERM ollama
	sleep 2
	success "Ollama 已停止"
else
	warning "Ollama 未运行"
fi

# 步骤10: 停止数据库服务 (优雅地)
log "步骤10: 停止数据库服务..."

# Redis
if pgrep -f "redis-server" >/dev/null; then
	log "  停止 Redis..."
	redis-cli shutdown 2>/dev/null || true
	sleep 3
	if pgrep -f "redis-server" >/dev/null; then
		pkill -TERM redis-server
		sleep 2
	fi
	success "Redis 已停止"
else
	warning "Redis 未运行"
fi

# PostgreSQL
if pgrep -f "postgres" >/dev/null; then
	log "  停止 PostgreSQL..."
	pg_ctl -D /Users/accusys/momentry/var/postgresql stop -m fast 2>/dev/null || true
	sleep 5
	if pgrep -f "postgres" >/dev/null; then
		pkill -TERM postgres
		sleep 3
	fi
	success "PostgreSQL 已停止"
else
	warning "PostgreSQL 未运行"
fi

# MongoDB
if pgrep -f "mongod" >/dev/null; then
	log "  停止 MongoDB..."
	mongod --dbpath /opt/homebrew/var/mongodb --shutdown 2>/dev/null || true
	sleep 5
	if pgrep -f "mongod" >/dev/null; then
		pkill -TERM mongod
		sleep 3
	fi
	success "MongoDB 已停止"
else
	warning "MongoDB 未运行"
fi

# MariaDB
if pgrep -f "mariadbd" >/dev/null; then
	log "  停止 MariaDB..."
	mysqladmin -u root shutdown 2>/dev/null || true
	sleep 5
	if pgrep -f "mariadbd" >/dev/null; then
		pkill -TERM mariadbd
		sleep 3
	fi
	success "MariaDB 已停止"
else
	warning "MariaDB 未运行"
fi

# Qdrant
if pgrep -f "qdrant" >/dev/null; then
	log "  停止 Qdrant..."
	pkill -TERM qdrant
	sleep 3
	success "Qdrant 已停止"
else
	warning "Qdrant 未运行"
fi

# 步骤11: 验证所有服务已停止
log "步骤11: 验证所有服务状态..."
echo ""

services=(
	"momentry server:momentry"
	"redis-server:redis"
	"postgres:postgresql"
	"mongod:mongodb"
	"mariadbd:mariadb"
	"qdrant:qdrant"
	"gitea web:gitea"
	"sftpgo serve:sftpgo"
	"caddy:caddy"
	"php-fpm:php-fpm"
	"n8n:n8n"
	"ollama:ollama"
	"node_monitor.sh:monitor"
)

all_stopped=true
for service in "${services[@]}"; do
	process="${service%:*}"
	name="${service#*:}"

	if pgrep -f "$process" >/dev/null; then
		error "$name 仍在运行"
		all_stopped=false
	else
		success "$name 已停止"
	fi
done

echo ""
echo "================================================"
if $all_stopped; then
	success "所有服务已优雅停止！"
	echo ""
	echo "系统现在可以安全关机。"
	echo "您可以使用以下命令关机："
	echo "  sudo shutdown -h now"
	echo ""
	echo "或者等待计划关机时间：18:20"
else
	warning "部分服务仍在运行。"
	echo ""
	echo "建议手动检查并停止这些服务后再关机。"
	echo "运行以下命令查看仍在运行的服务："
	echo "  ps aux | grep -E \"(momentry|redis|postgres|mongod|qdrant|gitea|sftpgo|caddy|php-fpm|mariadb|n8n|ollama)\" | grep -v grep"
fi
echo "================================================"

# 保存关机状态
echo "$(date): 系统关机准备完成" >/tmp/momentry_shutdown_prepared.log

exit 0
