#!/bin/bash
# setup_service.sh - 設定 systemd 服務（需要 sudo 權限）

set -e

USER_NAME=$(whoami)
APP_DIR="$HOME/momo_pro_system"

echo "=========================================="
echo "設定 systemd 服務"
echo "=========================================="

# 建立主服務檔案
echo "📝 建立 momo.service..."
sudo tee /etc/systemd/system/momo.service > /dev/null <<EOF
[Unit]
Description=Momo Pro System - Flask Application
After=network.target

[Service]
Type=simple
User=$USER_NAME
WorkingDirectory=$APP_DIR
Environment="PATH=$APP_DIR/venv/bin"
ExecStart=$APP_DIR/venv/bin/python app.py
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF

# 建立排程服務檔案
echo "📝 建立 momo-scheduler.service..."
sudo tee /etc/systemd/system/momo-scheduler.service > /dev/null <<EOF
[Unit]
Description=Momo Pro System - Scheduler
After=network.target

[Service]
Type=simple
User=$USER_NAME
WorkingDirectory=$APP_DIR
Environment="PATH=$APP_DIR/venv/bin"
ExecStart=$APP_DIR/venv/bin/python scheduler.py
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF

# 重新載入 systemd
echo "🔄 重新載入 systemd..."
sudo systemctl daemon-reload

# 啟用服務
echo "✅ 啟用服務..."
sudo systemctl enable momo
sudo systemctl enable momo-scheduler

echo ""
echo "✅ 服務設定完成！"
echo ""
echo "可以使用以下指令："
echo "  啟動服務： sudo systemctl start momo"
echo "  查看狀態： sudo systemctl status momo"
echo "  查看日誌： sudo journalctl -u momo -f"
echo "  重啟服務： sudo systemctl restart momo"
