#!/bin/bash

# Nomad 笔记本设置脚本 - Mac/Linux 版本
# 用于将 Mac 或 Linux 笔记本加入 Nomad 集群作为 server

set -e

# 配置变量
NOMAD_VERSION="1.10.5"
NOMAD_DATACENTER="dc1"
NOMAD_ENCRYPT_KEY="NVOMDvXblgWfhtzFzOUIHnKEOrbXOkPrkIPbRGGf1YQ="

# 检测操作系统
OS=$(uname -s | tr '[:upper:]' '[:lower:]')
ARCH=$(uname -m)

case $ARCH in
    x86_64) ARCH="amd64" ;;
    arm64|aarch64) ARCH="arm64" ;;
    *) echo "不支持的架构: $ARCH"; exit 1 ;;
esac

echo "🚀 开始设置 Nomad ($OS-$ARCH)..."

# 1. 检查 Tailscale
echo "📡 检查 Tailscale 连接..."
if ! command -v tailscale &> /dev/null; then
    echo "❌ 请先安装 Tailscale"
    exit 1
fi

TAILSCALE_IP=$(tailscale ip | head -1)
if [ -z "$TAILSCALE_IP" ]; then
    echo "❌ Tailscale 未连接，请先运行: tailscale up"
    exit 1
fi

echo "✅ Tailscale IP: $TAILSCALE_IP"

# 2. 安装 Nomad（如果需要）
if ! command -v nomad &> /dev/null; then
    echo "📦 安装 Nomad $NOMAD_VERSION..."
    
    if [[ "$OS" == "darwin" ]]; then
        # macOS
        if command -v brew &> /dev/null; then
            brew install nomad
        else
            echo "❌ 请先安装 Homebrew 或手动安装 Nomad"
            exit 1
        fi
    else
        # Linux
        NOMAD_URL="https://releases.hashicorp.com/nomad/${NOMAD_VERSION}/nomad_${NOMAD_VERSION}_${OS}_${ARCH}.zip"
        curl -L "$NOMAD_URL" -o nomad.zip
        unzip nomad.zip
        sudo mv nomad /usr/local/bin/
        rm nomad.zip
    fi
fi

echo "✅ Nomad 版本: $(nomad version)"

# 3. 创建配置目录
echo "📁 创建配置目录..."
sudo mkdir -p /etc/nomad.d /opt/nomad/data
sudo chown -R $(whoami):$(id -gn) /etc/nomad.d /opt/nomad/data

# 4. 生成 Nomad 配置
echo "⚙️  生成 Nomad 配置..."
cat > /etc/nomad.d/nomad.hcl << EOF
datacenter = "$NOMAD_DATACENTER"
data_dir = "/opt/nomad/data"
log_level = "INFO"

bind_addr = "$TAILSCALE_IP"

addresses {
  http = "0.0.0.0"
  rpc  = "$TAILSCALE_IP"
  serf = "$TAILSCALE_IP"
}

ports {
  http = 4646
  rpc  = 4647
  serf = 4648
}

server {
  enabled = true
  bootstrap_expect = 6
  
  retry_join = [
    "100.116.158.95",   # semaphore
    "100.117.106.136",  # master (现在是 client)
    "100.116.80.94"     # ash3c (现在是 client)
  ]
  
  encrypt = "$NOMAD_ENCRYPT_KEY"
}

client {
  enabled = false
}

# 如果是 macOS，可能需要 Docker 插件
plugin "podman" {
  config {
    volumes {
      enabled = true
    }
  }
}

consul {
  address = "$TAILSCALE_IP:8500"
}
EOF

echo "✅ 配置文件已生成: /etc/nomad.d/nomad.hcl"

# 5. 创建启动脚本（macOS 不使用 systemd）
if [[ "$OS" == "darwin" ]]; then
    # macOS - 创建 LaunchDaemon
    echo "🍎 创建 macOS LaunchDaemon..."
    sudo tee /Library/LaunchDaemons/io.nomadproject.nomad.plist > /dev/null << EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>io.nomadproject.nomad</string>
    <key>ProgramArguments</key>
    <array>
        <string>/usr/local/bin/nomad</string>
        <string>agent</string>
        <string>-config=/etc/nomad.d/nomad.hcl</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>StandardOutPath</key>
    <string>/var/log/nomad.log</string>
    <key>StandardErrorPath</key>
    <string>/var/log/nomad.log</string>
</dict>
</plist>
EOF
    
    # 加载并启动服务
    sudo launchctl load /Library/LaunchDaemons/io.nomadproject.nomad.plist
    sudo launchctl start io.nomadproject.nomad
    
else
    # Linux - 创建 systemd 服务
    echo "🐧 创建 systemd 服务..."
    sudo tee /etc/systemd/system/nomad.service > /dev/null << EOF
[Unit]
Description=Nomad
Documentation=https://www.nomadproject.io/
Requires=network-online.target
After=network-online.target

[Service]
Type=notify
User=$(whoami)
Group=$(id -gn)
ExecStart=/usr/local/bin/nomad agent -config=/etc/nomad.d/nomad.hcl
ExecReload=/bin/kill -HUP \$MAINPID
KillMode=process
Restart=on-failure
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target
EOF
    
    # 启动服务
    sudo systemctl daemon-reload
    sudo systemctl enable nomad
    sudo systemctl start nomad
fi

# 6. 验证安装
echo "🔍 验证 Nomad 服务..."
sleep 5

if [[ "$OS" == "darwin" ]]; then
    if sudo launchctl list | grep -q nomad; then
        echo "✅ Nomad 服务已启动"
    else
        echo "❌ Nomad 服务启动失败"
        exit 1
    fi
else
    if systemctl is-active --quiet nomad; then
        echo "✅ Nomad 服务已启动"
    else
        echo "❌ Nomad 服务启动失败"
        sudo systemctl status nomad
        exit 1
    fi
fi

# 7. 检查集群状态
echo "🌐 检查集群连接..."
sleep 10

if nomad server members 2>/dev/null | grep -q alive; then
    echo "✅ 成功加入 Nomad 集群！"
    nomad server members
else
    echo "⚠️  正在连接集群，请稍等..."
    echo "可以运行以下命令检查状态："
    echo "  nomad server members"
    echo "  nomad node status"
fi

echo ""
echo "🎉 设置完成！"
echo "📊 Web UI: http://$TAILSCALE_IP:4646"
echo "🔧 配置文件: /etc/nomad.d/nomad.hcl"
echo "📝 日志查看:"
if [[ "$OS" == "darwin" ]]; then
    echo "  tail -f /var/log/nomad.log"
else
    echo "  sudo journalctl -u nomad -f"
fi