#!/bin/bash

# Nomad集群NFS配置部署脚本
# 根据容器类型和地理位置进行分情况处理

set -e

echo "🚀 开始部署Nomad集群NFS配置..."

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

# 函数：打印带颜色的消息
log_info() { echo -e "${GREEN}[INFO]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

# 检查当前目录
if [ ! -f "configuration/inventories/production/inventory.ini" ]; then
    log_error "请在mgmt项目根目录运行此脚本"
    exit 1
fi

# 1. 为所有节点配置NFS挂载
log_info "步骤1: 为所有节点配置NFS挂载 (根据容器类型和地理位置)"
ansible-playbook -i configuration/inventories/production/inventory.ini \
    playbooks/setup-nfs-by-container-type.yml

# 2. 为Nomad客户端配置NFS卷支持
log_info "步骤2: 配置Nomad客户端支持NFS卷"
ansible-playbook -i configuration/inventories/production/nomad-cluster.ini \
    playbooks/setup-nomad-nfs-client.yml

# 3. 验证NFS挂载状态
log_info "步骤3: 验证所有节点的NFS挂载状态"
ansible all -i configuration/inventories/production/inventory.ini \
    -m shell -a "df -h /mnt/fnsync 2>/dev/null || echo 'NFS未挂载'" \
    --limit '!snail'

# 4. 验证Nomad客户端配置
log_info "步骤4: 验证Nomad客户端配置"
ansible nomad_clients -i configuration/inventories/production/nomad-cluster.ini \
    -m shell -a "nomad node status -self 2>/dev/null || echo 'Nomad未运行'"

# 5. 部署示例NFS任务（可选）
read -p "是否部署示例NFS任务？(y/n): " deploy_example
if [ "$deploy_example" = "y" ] || [ "$deploy_example" = "Y" ]; then
    log_info "部署示例NFS任务..."
    nomad run jobs/nomad-nfs-multi-type.nomad
    echo "等待任务启动..."
    sleep 10
    nomad job status nfs-multi-type-example
fi

log_info "✅ NFS配置部署完成!"
echo ""
echo "📋 使用说明:"
echo "1. NFS挂载点: /mnt/fnsync"
echo "2. 本地LXC容器: 直接使用挂载目录"
echo "3. 海外PVE容器: 使用优化参数挂载"
echo "4. Nomad作业: 使用host volume 'nfs-shared'"
echo ""
echo "🔧 手动验证命令:"
echo "  - 检查NFS挂载: df -h /mnt/fnsync"
echo "  - 检查Nomad状态: nomad node status"
echo "  - 运行NFS任务: nomad run jobs/nomad-nfs-multi-type.nomad"