# 🛠️ ROA2WEB Windows Deployment Scripts

Complete reference for ROA2WEB Windows deployment PowerShell scripts (v2.0 - Unified System).

## 📋 Script Overview

### ⭐ Unified Scripts (Recommended)

#### **Build-ROA2WEB.ps1** - Unified Build System
**Purpose**: Build deployment packages for all components with interactive menu

**Usage**:
```powershell
# Interactive mode - shows menu
.\Build-ROA2WEB.ps1

# Non-interactive mode - specific component
.\Build-ROA2WEB.ps1 -Component All           # Complete package
.\Build-ROA2WEB.ps1 -Component Frontend      # Frontend + Backend
.\Build-ROA2WEB.ps1 -Component Backend       # Backend only
.\Build-ROA2WEB.ps1 -Component TelegramBot   # Telegram Bot only

# Custom output path
.\Build-ROA2WEB.ps1 -Component All -OutputPath "D:\builds\roa2web-$(Get-Date -Format 'yyyyMMdd')"
```

**Interactive Menu**:
```
[1] All Components (Frontend + Backend + Telegram Bot)
[2] Frontend + Backend (Vue.js build + FastAPI backend)
[3] Backend Only (FastAPI backend + shared modules)
[4] Telegram Bot Only (Standalone package)
[Q] Quit
```

**Parameters**:
- `-Component` All|Frontend|Backend|TelegramBot (optional - shows menu if not specified)
- `-OutputPath` (default: `./deploy-package`)
- `-Clean` $true|$false (default: $true)

**Features**:
- ✅ Interactive menu for component selection
- ✅ Isolated temp directory for frontend builds (doesn't corrupt WSL node_modules)
- ✅ Automatic dependency installation (including devDependencies)
- ✅ Auto-cleanup after build
- ✅ Generates deployment README

**Output**: Creates `deploy-package/` with complete deployment files

---

#### **ROA2WEB-Console.ps1** - Unified Deployment & Management Console
**Purpose**: All-in-one console for deploying and managing ROA2WEB services

**Usage**:
```powershell
# Interactive mode - shows main menu
.\ROA2WEB-Console.ps1

# Non-interactive mode - specific actions
.\ROA2WEB-Console.ps1 -NonInteractive -Action DeployAll
.\ROA2WEB-Console.ps1 -NonInteractive -Action DeployBackend
.\ROA2WEB-Console.ps1 -NonInteractive -Action DeployTelegramBot
.\ROA2WEB-Console.ps1 -NonInteractive -Action StartAll
.\ROA2WEB-Console.ps1 -NonInteractive -Action StopAll
.\ROA2WEB-Console.ps1 -NonInteractive -Action RestartAll
.\ROA2WEB-Console.ps1 -NonInteractive -Action Status
```

**Interactive Main Menu**:
```
[1] Deploy Components
    - Deploy Backend + Frontend
    - Deploy Telegram Bot
    - Deploy All Components

[2] Manage Services
    - Start/Stop/Restart All
    - Start/Stop/Restart Backend
    - Start/Stop/Restart Telegram Bot

[3] Check Status
    - Service status
    - Health checks

[Q] Quit
```

**Parameters**:
- `-NonInteractive` Switch to enable non-interactive mode
- `-Action` DeployBackend|DeployTelegramBot|DeployAll|StartAll|StopAll|RestartAll|Status

**Features**:
- ✅ Unified interface for deploy + management
- ✅ Interactive menus with easy navigation
- ✅ Automatic backups before deployment
- ✅ Smart dependency updates (only if requirements.txt changed)
- ✅ Health checks after operations
- ✅ Color-coded status output
- ✅ Both interactive and non-interactive modes
- ✅ Preserves .env configuration files

**Replaces**:
- ❌ `Deploy-ROA2WEB.ps1` (removed)
- ❌ `Deploy-TelegramBot.ps1` (removed)
- ❌ `Manage-ROA2WEB.ps1` (removed)

---

### 🚀 Installation Scripts (First-Time Setup)

#### **Install-ROA2WEB.ps1**
**Purpose**: First-time installation of Backend + Frontend

**Usage**:
```powershell
.\Install-ROA2WEB.ps1

# Custom parameters
.\Install-ROA2WEB.ps1 -InstallPath "C:\Apps\roa2web" -ServicePort 8000
```

**What it does**:
1. Installs Chocolatey, Python 3.11+, NSSM
2. Installs IIS URL Rewrite & ARR modules
3. Creates directory structure
4. Creates Python virtual environment
5. Installs Python dependencies
6. Creates Windows Service (ROA2WEB-Backend)
7. Configures IIS website & application

**Parameters**:
- `-InstallPath` (default: `C:\inetpub\wwwroot\roa2web`)
- `-ServicePort` (default: 8000)
- `-IISSiteName`, `-IISAppName`
- `-CreateNewSite`, `-SkipPython`, `-SkipIIS`

---

#### **Install-TelegramBot.ps1**
**Purpose**: First-time installation of Telegram Bot

**Usage**:
```powershell
.\Install-TelegramBot.ps1

# Custom parameters
.\Install-TelegramBot.ps1 -InstallPath "C:\Apps\telegram-bot" -ServicePort 8002
```

**What it does**:
1. Validates Python 3.11+ installation
2. Installs NSSM (if needed)
3. Creates directory structure (data/, logs/, backups/)
4. Creates Python virtual environment
5. Installs Python dependencies
6. Creates Windows Service (ROA2WEB-TelegramBot)
7. Creates .env template

**Parameters**:
- `-InstallPath` (default: `C:\inetpub\wwwroot\roa2web\telegram-bot`)
- `-ServicePort` (default: 8002)
- `-SourcePath` (auto-detected)

---

### 🛠️ Utility Scripts

#### **Backup-TelegramDB.ps1**
**Purpose**: Backup Telegram bot SQLite database

**Usage**:
```powershell
# Basic backup
.\Backup-TelegramDB.ps1

# Compressed backup
.\Backup-TelegramDB.ps1 -Compress $true

# Keep more backups
.\Backup-TelegramDB.ps1 -RetentionCount 20
```

**What it does**:
1. Stops bot service gracefully
2. Creates timestamped backup of `telegram_bot.db`
3. Optionally compresses backup
4. Restarts service
5. Cleans old backups (configurable retention)

---

#### **Setup-DailyBackup.ps1**
**Purpose**: Schedule automated daily database backups

**Usage**:
```powershell
# Setup daily backup at 2 AM
.\Setup-DailyBackup.ps1

# Custom time and retention
.\Setup-DailyBackup.ps1 -Time "03:00" -RetentionDays 30
```

**What it does**:
1. Creates Windows Scheduled Task
2. Runs `Backup-TelegramDB.ps1` daily at specified time
3. Configurable time, retention, and compression

---

#### **Setup-ClaudeAuth.ps1**
**Purpose**: Setup Claude API authentication for Telegram bot

**Usage**:
```powershell
.\Setup-ClaudeAuth.ps1
```

**What it does**:
1. **Method 1 (Recommended)**: Browser-based Claude Pro/Max login
   - Runs `claude-code login` if available
   - Copies credentials to bot installation directory
2. **Method 2**: Manual API key entry
3. Validates credentials
4. Updates .env file
5. Restarts bot service

**Features**:
- ✅ Supports both Claude Pro/Max and API key
- ✅ Auto-detects credentials location
- ✅ Validates authentication before applying

---

#### **Enable-HTTPS.ps1**
**Purpose**: Enable HTTPS for IIS website

**Usage**:
```powershell
# Create self-signed certificate
.\Enable-HTTPS.ps1

# Use existing certificate
.\Enable-HTTPS.ps1 -CertPath "C:\Certs\roa2web.pfx" -CertPassword "password"
```

**What it does**:
1. Creates/imports SSL certificate
2. Configures HTTPS binding (port 443)
3. Enables HTTP to HTTPS redirect
4. Activates HSTS (HTTP Strict Transport Security)

---

## 🚀 Quick Reference Guide

### 📦 First-Time Deployment Workflow

```powershell
# ========================================
# STEP 1: Build on Development Machine (WSL/Linux)
# ========================================
cd deployment/windows/scripts
.\Build-ROA2WEB.ps1
# Select [1] All Components from menu

# ========================================
# STEP 2: Transfer Package to Windows Server
# ========================================
# Transfer deploy-package/ to server (e.g., C:\Deploy\roa2web-package)

# ========================================
# STEP 3: Install on Windows Server (as Administrator)
# ========================================
cd C:\Deploy\roa2web-package\scripts

# Install Backend + Frontend
.\Install-ROA2WEB.ps1

# Install Telegram Bot
.\Install-TelegramBot.ps1

# ========================================
# STEP 4: Configure
# ========================================
notepad C:\inetpub\wwwroot\roa2web\backend\.env
notepad C:\inetpub\wwwroot\roa2web\telegram-bot\.env

# ========================================
# STEP 5: Start Services via Console
# ========================================
.\ROA2WEB-Console.ps1
# Select [2] Manage Services -> [1] Start All Services
```

---

### 🔄 Deploy Updates Workflow

```powershell
# ========================================
# STEP 1: Build New Package on Development Machine
# ========================================
cd deployment/windows/scripts
.\Build-ROA2WEB.ps1
# Select component to update from menu

# ========================================
# STEP 2: Transfer to Windows Server
# ========================================
# Transfer new deploy-package/ to server

# ========================================
# STEP 3: Deploy via Console (as Administrator)
# ========================================
cd C:\Deploy\new-package\scripts
.\ROA2WEB-Console.ps1

# Option A: Interactive Menu
# [1] Deploy Components -> Select what to deploy

# Option B: Non-Interactive
.\ROA2WEB-Console.ps1 -NonInteractive -Action DeployAll
```

---

### 🎛️ Daily Operations via Console

```powershell
# Launch console
.\ROA2WEB-Console.ps1

# Main Menu Navigation:
# [1] Deploy Components   -> Deploy/update application files
# [2] Manage Services     -> Start/Stop/Restart services
# [3] Check Status        -> View service status and health
# [Q] Quit

# Non-Interactive Quick Commands:
.\ROA2WEB-Console.ps1 -NonInteractive -Action Status
.\ROA2WEB-Console.ps1 -NonInteractive -Action RestartAll
```

---

### 📊 Utility Operations

```powershell
# Backup database
.\Backup-TelegramDB.ps1

# Setup automated daily backups
.\Setup-DailyBackup.ps1 -Time "02:00" -RetentionDays 14

# Configure Claude API
.\Setup-ClaudeAuth.ps1

# Enable HTTPS
.\Enable-HTTPS.ps1
```

---

## 📊 Script Comparison: v1.0 vs v2.0

| Capability | v1.0 (Old) | v2.0 (Unified) |
|-----------|-----------|----------------|
| **Build Scripts** | 3 separate | 1 unified (`Build-ROA2WEB.ps1`) |
| **Deploy Scripts** | 2 separate | 1 unified console (`ROA2WEB-Console.ps1`) |
| **Manage Scripts** | 1 basic | Integrated in console |
| **Total Scripts** | 13 scripts | 8 scripts |
| **Interactive Menus** | ❌ No | ✅ Yes |
| **Non-Interactive Mode** | ⚠️ Partial | ✅ Full support |
| **Health Checks** | ⚠️ Basic | ✅ Comprehensive |
| **Backup Management** | ⚠️ Manual | ✅ Automatic |
| **Dependency Updates** | ⚠️ Always reinstall | ✅ Smart (only if changed) |
| **WSL Compatibility** | ❌ Corrupts node_modules | ✅ Isolated builds |

---

## 🗂️ Complete Script List (v2.0)

### Core Scripts (2)
1. ⭐ **Build-ROA2WEB.ps1** - Unified build system with menu
2. ⭐ **ROA2WEB-Console.ps1** - Unified deployment & management console

### Installation Scripts (2)
3. **Install-ROA2WEB.ps1** - First-time Backend + Frontend setup
4. **Install-TelegramBot.ps1** - First-time Telegram Bot setup

### Utility Scripts (4)
5. **Backup-TelegramDB.ps1** - Database backup
6. **Setup-DailyBackup.ps1** - Automated backup scheduling
7. **Setup-ClaudeAuth.ps1** - Claude API configuration
8. **Enable-HTTPS.ps1** - HTTPS setup for IIS

### Removed Scripts (5)
- ❌ `Build-Frontend.ps1` → Use `Build-ROA2WEB.ps1 -Component Frontend`
- ❌ `Build-TelegramBot.ps1` → Use `Build-ROA2WEB.ps1 -Component TelegramBot`
- ❌ `Deploy-ROA2WEB.ps1` → Use `ROA2WEB-Console.ps1` menu option [1] Deploy
- ❌ `Deploy-TelegramBot.ps1` → Use `ROA2WEB-Console.ps1` menu option [1] Deploy
- ❌ `Manage-ROA2WEB.ps1` → Use `ROA2WEB-Console.ps1` menu option [2] Manage

---

## 💡 Best Practices

### Development Machine (WSL/Linux)
```powershell
# Always use Build-ROA2WEB.ps1 for building
# It isolates npm builds to prevent WSL corruption
.\Build-ROA2WEB.ps1
```

### Windows Server
```powershell
# Use ROA2WEB-Console.ps1 for all operations
# Interactive mode for manual operations
.\ROA2WEB-Console.ps1

# Non-interactive mode for automation/scripts
.\ROA2WEB-Console.ps1 -NonInteractive -Action DeployAll
```

### Configuration Management
- ✅ `.env` files are NEVER overwritten during deployment
- ✅ Backups are created automatically before any deployment
- ✅ Old backups are auto-cleaned (keeps last 10)
- ✅ Dependencies only reinstalled if `requirements.txt` changes

### Service Management
- ✅ Always use ROA2WEB-Console for service operations
- ✅ Health checks are automatic after service starts
- ✅ Color-coded output makes status clear
- ✅ Services can be managed individually or together

---

## 🐛 Troubleshooting

### Script Execution Policy Error
```powershell
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
```

### Build Fails on WSL
- Ensure Node.js 16+ is installed: `node -v`
- Close all IDEs (file locks prevent builds)
- Run as Administrator in PowerShell

### Service Won't Start
```powershell
# Check status via console
.\ROA2WEB-Console.ps1 -NonInteractive -Action Status

# View backend logs
Get-Content C:\inetpub\wwwroot\roa2web\logs\backend-stderr.log -Tail 50

# View Telegram bot logs
Get-Content C:\inetpub\wwwroot\roa2web\telegram-bot\logs\stderr.log -Tail 50
```

### Deployment Fails
```powershell
# ROA2WEB-Console.ps1 creates automatic backups
# Check backup location if rollback needed
Get-ChildItem C:\inetpub\wwwroot\roa2web\backups\ | Sort-Object Name -Descending
```

### Frontend Build Corrupts WSL node_modules
- ✅ **Fixed in v2.0!** Build-ROA2WEB.ps1 uses isolated temp directory
- The temp directory is automatically cleaned after build

---

## 📚 Documentation

- **Quick Start**: [`../README.md`](../README.md)
- **Complete Deployment Guide**: [`../docs/WINDOWS_DEPLOYMENT.md`](../docs/WINDOWS_DEPLOYMENT.md)
- **Deployment Package Guide**: [`../DEPLOY_PACKAGE.md`](../DEPLOY_PACKAGE.md)
- **Telegram Bot Troubleshooting**: [`../docs/TELEGRAM_BOT_TROUBLESHOOTING.md`](../docs/TELEGRAM_BOT_TROUBLESHOOTING.md)
- **HTTPS Setup**: [`../docs/HTTPS_SETUP.md`](../docs/HTTPS_SETUP.md)
- **Project Documentation**: [`../../../CLAUDE.md`](../../../CLAUDE.md)

---

**Version**: 2.0 (Unified System)
**Last Updated**: 2025-11-12
**Author**: ROA2WEB Team
