#!/bin/bash
# =============================================================================
# Sentry Self-Hosted 部署腳本
# =============================================================================
# 目標主機: 192.168.0.110 (DevOps 金庫)
# 用途: Error Tracking + Session Replay (補強 SignOz)
# 執行: ssh wooo@192.168.0.110 'bash -s' < deploy.sh
# =============================================================================

set -euo pipefail

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

SENTRY_VERSION="24.3.0"  # 使用穩定版本
INSTALL_DIR="/opt/sentry"

echo -e "${YELLOW}=== Sentry Self-Hosted 部署 ===${NC}"
echo "目標目錄: ${INSTALL_DIR}"
echo "版本: ${SENTRY_VERSION}"

# 檢查 Docker
if ! command -v docker &> /dev/null; then
    echo -e "${RED}錯誤: Docker 未安裝${NC}"
    exit 1
fi

# 檢查 Docker Compose
if ! docker compose version &> /dev/null; then
    echo -e "${RED}錯誤: Docker Compose V2 未安裝${NC}"
    exit 1
fi

# 檢查系統資源
MEM_GB=$(free -g | awk '/^Mem:/{print $2}')
if [ "$MEM_GB" -lt 8 ]; then
    echo -e "${YELLOW}警告: 記憶體 ${MEM_GB}GB < 8GB (建議 16GB)${NC}"
fi

# 建立安裝目錄
sudo mkdir -p "$INSTALL_DIR"
cd "$INSTALL_DIR"

# 下載 Sentry Self-Hosted
if [ ! -d ".git" ]; then
    echo -e "${GREEN}下載 Sentry Self-Hosted...${NC}"
    sudo git clone https://github.com/getsentry/self-hosted.git .
    sudo git checkout "${SENTRY_VERSION}"
fi

# 執行官方安裝腳本
echo -e "${GREEN}執行安裝腳本...${NC}"
sudo ./install.sh

echo -e "${GREEN}=== 安裝完成 ===${NC}"
echo ""
echo "後續步驟:"
echo "1. 啟動服務: cd ${INSTALL_DIR} && docker compose up -d"
echo "2. 建立管理員: docker compose run --rm web createuser"
echo "3. 建立專案: awoooi-web, awoooi-api"
echo "4. 取得 DSN 並配置到 K8s ConfigMap"
echo ""
echo "Sentry UI: http://192.168.0.110:9000"
