#!/usr/bin/env bash
# =========================================================
# Bark Server 一键安装脚本
# 作者：ChatGPT GPT-5
# 功能：
#   - 自动检测系统架构
#   - 下载最新 bark-server 可执行文件
#   - 创建数据目录 /home/bark/data
#   - 赋予执行权限
#   - 设置 systemd 服务（支持开机自启）
#   - 启动 bark-server
# =========================================================

set -e

# ---------- 配置 ----------
BARK_DIR="/home/bark"
BARK_DATA="${BARK_DIR}/data"
BARK_BIN="${BARK_DIR}/bark-server"
BARK_PORT="8080"
BARK_ADDR="0.0.0.0:${BARK_PORT}"
GITHUB_API="https://api.github.com/repos/Finb/bark-server/releases/latest"

# ---------- 准备 ----------
echo "📦 正在准备 Bark 目录..."
mkdir -p "${BARK_DATA}"
cd "${BARK_DIR}"

# ---------- 检测架构 ----------
ARCH=$(uname -m)
case "$ARCH" in
    x86_64) ARCH_NAME="amd64" ;;
    aarch64|arm64) ARCH_NAME="arm64" ;;
    armv7l) ARCH_NAME="armv7" ;;
    *) echo "❌ 不支持的架构: $ARCH"; exit 1 ;;
esac
echo "✅ 检测到系统架构: ${ARCH_NAME}"

# ---------- 获取下载链接 ----------
echo "🌐 正在获取 Bark 最新版本下载链接..."
DOWNLOAD_URL=$(curl -sL "${GITHUB_API}" | grep "browser_download_url" | grep "linux_${ARCH_NAME}" | head -n 1 | cut -d '"' -f 4)

if [ -z "$DOWNLOAD_URL" ]; then
    echo "❌ 未能获取 Bark 下载地址，请检查网络或 GitHub 可用性。"
    exit 1
fi

echo "✅ 最新版本下载地址: $DOWNLOAD_URL"

# ---------- 下载 ----------
echo "⬇️ 正在下载 bark-server..."
curl -L -o "${BARK_BIN}" "$DOWNLOAD_URL"

# ---------- 赋权 ----------
chmod +x "${BARK_BIN}"

# ---------- 创建 systemd 服务 ----------
SERVICE_FILE="/etc/systemd/system/bark.service"

echo "⚙️ 创建 systemd 服务: ${SERVICE_FILE}"

cat > "${SERVICE_FILE}" <<EOF
[Unit]
Description=Bark Push Notification Server
After=network.target

[Service]
Type=simple
ExecStart=${BARK_BIN} -addr ${BARK_ADDR} -data ${BARK_DATA}
Restart=always
RestartSec=5
User=root
WorkingDirectory=${BARK_DIR}

[Install]
WantedBy=multi-user.target
EOF

# ---------- 重新加载并启动 ----------
systemctl daemon-reload
systemctl enable bark.service
systemctl restart bark.service

# ---------- 状态检查 ----------
sleep 1
if systemctl is-active --quiet bark.service; then
    echo "✅ Bark Server 已启动成功！"
    echo "📡 访问地址: http://$(hostname -I | awk '{print $1}'):${BARK_PORT}"
    echo "📂 数据目录: ${BARK_DATA}"
    echo "🔧 可执行文件: ${BARK_BIN}"
else
    echo "❌ Bark Server 启动失败，请运行以下命令查看日志："
    echo "   journalctl -u bark.service -e"
fi
