#!/bin/bash
# SalesPipeline 部署腳本
# 使用方式: ./deploy.sh

set -e

echo "=========================================="
echo "  SalesPipeline Deployment Script"
echo "=========================================="

# 設定變數
APP_DIR="/opt/salespipeline"
BACKEND_DIR="$APP_DIR/backend"
FRONTEND_DIR="$APP_DIR/frontend"
SERVICE_NAME="salespipeline"
LOG_DIR="/var/log/salespipeline"

# 顏色輸出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

print_status() {
    echo -e "${GREEN}[✓]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[!]${NC} $1"
}

print_error() {
    echo -e "${RED}[✗]${NC} $1"
}

# 1. 建立目錄
echo ""
echo "Step 1: Creating directories..."
sudo mkdir -p $APP_DIR
sudo mkdir -p $LOG_DIR
sudo chown -R $USER:$USER $APP_DIR
print_status "Directories created"

# 2. 設定 Python 虛擬環境
echo ""
echo "Step 2: Setting up Python environment..."
cd $BACKEND_DIR
python3 -m venv venv
source venv/bin/activate
pip install --upgrade pip
pip install -r requirements.txt
print_status "Python environment ready"

# 3. 設定環境變數
echo ""
echo "Step 3: Configuring environment..."
if [ ! -f "$BACKEND_DIR/.env" ]; then
    if [ -f "$BACKEND_DIR/.env.example" ]; then
        cp $BACKEND_DIR/.env.example $BACKEND_DIR/.env
        print_warning "Created .env from .env.example - please update with production values"
    else
        print_error ".env.example not found"
        exit 1
    fi
else
    print_status ".env file exists"
fi

# 4. 建置前端
echo ""
echo "Step 4: Building frontend..."
cd $FRONTEND_DIR
if command -v npm &> /dev/null; then
    npm install
    npm run build
    print_status "Frontend built successfully"
else
    print_warning "npm not found - skipping frontend build"
fi

# 5. 設定 Systemd 服務
echo ""
echo "Step 5: Configuring systemd service..."
sudo cp $APP_DIR/deploy/salespipeline.service /etc/systemd/system/
sudo systemctl daemon-reload
print_status "Systemd service configured"

# 6. 設定目錄權限
echo ""
echo "Step 6: Setting permissions..."
sudo chown -R www-data:www-data $BACKEND_DIR/data
sudo chown -R www-data:www-data $BACKEND_DIR/static
sudo chown -R www-data:www-data $LOG_DIR
print_status "Permissions set"

# 7. 啟動服務
echo ""
echo "Step 7: Starting service..."
sudo systemctl enable $SERVICE_NAME
sudo systemctl restart $SERVICE_NAME
print_status "Service started"

# 8. 檢查狀態
echo ""
echo "Step 8: Checking status..."
sleep 2
if sudo systemctl is-active --quiet $SERVICE_NAME; then
    print_status "Service is running!"
else
    print_error "Service failed to start"
    sudo journalctl -u $SERVICE_NAME -n 20
    exit 1
fi

echo ""
echo "=========================================="
echo "  Deployment Complete!"
echo "=========================================="
echo ""
echo "Application URL: http://localhost:8000"
echo "Logs: sudo journalctl -u $SERVICE_NAME -f"
echo ""
