#!/bin/bash
# =============================================================================
# WOOO TECH - Momo Pro System
# UAT VM 開機自動啟動 Docker 服務配置腳本
# =============================================================================

set -e

echo "=========================================="
echo "配置 Docker 開機自動啟動"
echo "=========================================="

# 檢查是否為 root 或有 sudo 權限
if [ "$EUID" -ne 0 ]; then
    echo "請使用 sudo 執行此腳本"
    echo "用法: sudo bash setup_autostart.sh"
    exit 1
fi

# 1. 確保 Docker 服務開機自動啟動
echo ""
echo "[1/4] 啟用 Docker 服務開機自動啟動..."
systemctl enable docker
systemctl is-enabled docker

# 2. 確保 Docker 服務正在運行
echo ""
echo "[2/4] 確認 Docker 服務狀態..."
systemctl start docker
systemctl status docker --no-pager | head -5

# 3. 創建 Momo Pro System 的 systemd 服務
echo ""
echo "[3/4] 創建 Momo Pro System systemd 服務..."

# 獲取實際的安裝路徑
INSTALL_PATH="${INSTALL_PATH:-/home/wooo/momo_pro_system}"

cat > /etc/systemd/system/momo-docker.service << EOF
[Unit]
Description=Momo Pro System Docker Compose
Documentation=https://github.com/wooo-tech/momo-pro-system
Requires=docker.service
After=docker.service network-online.target
Wants=network-online.target

[Service]
Type=oneshot
RemainAfterExit=yes
WorkingDirectory=${INSTALL_PATH}
ExecStart=/usr/bin/docker compose --profile monitoring up -d
ExecStop=/usr/bin/docker compose --profile monitoring down
ExecReload=/usr/bin/docker compose --profile monitoring restart
TimeoutStartSec=300
TimeoutStopSec=120

[Install]
WantedBy=multi-user.target
EOF

echo "服務檔案已創建: /etc/systemd/system/momo-docker.service"

# 4. 啟用並啟動服務
echo ""
echo "[4/4] 啟用 Momo Pro System 服務..."
systemctl daemon-reload
systemctl enable momo-docker.service
systemctl is-enabled momo-docker.service

echo ""
echo "=========================================="
echo "✅ 配置完成！"
echo "=========================================="
echo ""
echo "服務管理命令："
echo "  啟動服務: sudo systemctl start momo-docker"
echo "  停止服務: sudo systemctl stop momo-docker"
echo "  重啟服務: sudo systemctl restart momo-docker"
echo "  查看狀態: sudo systemctl status momo-docker"
echo "  查看日誌: sudo journalctl -u momo-docker -f"
echo ""
echo "驗證自動啟動配置："
echo "  sudo systemctl is-enabled momo-docker"
echo ""
echo "如需修改安裝路徑，請設置環境變數："
echo "  sudo INSTALL_PATH=/your/path bash setup_autostart.sh"
echo ""
