# Ubuntu Server Deployment Guide

This guide will help you deploy the Aumentum API backend to an Ubuntu server.

## Prerequisites

- Ubuntu 20.04 LTS or later
- Root or sudo access
- Network access to:
  - MSSQL database server (10.10.10.5:1433)
  - Contentstore share (//10.10.10.5/LRS_STORAGE)
- At least 2GB RAM and 10GB disk space

## Quick Deployment

### 1. Run the Deployment Script

```bash
sudo bash scripts/deploy_ubuntu.sh
```

This script will:
- Install all system dependencies
- Configure FreeTDS and ODBC
- Create application user and directories
- Set up mount points

### 2. Copy Application Files

Copy your application to the server:

```bash
# Option 1: Using SCP
scp -r /path/to/plagis_aumentum user@server:/opt/

# Option 2: Using Git (recommended)
cd /opt
sudo git clone <your-repo-url> plagis_aumentum
sudo chown -R plagis:plagis plagis_aumentum
```

### 3. Set Up Python Environment

```bash
cd /opt/plagis_aumentum
sudo bash scripts/setup_application.sh
```

Or manually:
```bash
cd /opt/plagis_aumentum
sudo -u plagis python3 -m venv venv
sudo -u plagis venv/bin/pip install --upgrade pip
sudo -u plagis venv/bin/pip install -r requirements.txt
```

### 4. Mount Contentstore

Mount the Windows share containing the contentstore:

```bash
# Install CIFS utilities if not already installed
sudo apt-get install -y cifs-utils

# Create mount point
sudo mkdir -p /mnt/aumentum_contentstore

# Mount manually (for testing)
sudo mount -t cifs //10.10.10.5/LRS_STORAGE /mnt/aumentum_contentstore \
  -o credentials=/root/.smb_credentials_aumentum,uid=$(id -u plagis),gid=$(id -g plagis),file_mode=0755,dir_mode=0755

# Or add to /etc/fstab for automatic mounting
echo "//10.10.10.5/LRS_STORAGE /mnt/aumentum_contentstore cifs credentials=/root/.smb_credentials_aumentum,uid=$(id -u plagis),gid=$(id -g plagis),file_mode=0755,dir_mode=0755 0 0" | sudo tee -a /etc/fstab

# Test mount
sudo mount -a
```

### 5. Configure Environment Variables

Create a `.env` file (optional, for overriding defaults):

```bash
sudo -u plagis nano /opt/plagis_aumentum/.env
```

Example `.env` file:
```bash
# Contentstore path
CONTENTSTORE_BASE=/mnt/aumentum_contentstore/contentstore

# Database configuration
DB_SERVER=MSSQL_LRS43_PROD
DB_DATABASE=LRS43
DB_USERNAME=sa
DB_PASSWORD=Plagis$registry
DB_DRIVER=FreeTDS

# Cache directory
TEMP_PDF_DIR=/var/cache/plagis/pdfs
```

### 6. Install Systemd Service

```bash
# Copy service file
sudo cp scripts/plagis-aumentum-api.service /etc/systemd/system/

# If you created a .env file, uncomment the EnvironmentFile line in the service file
sudo nano /etc/systemd/system/plagis-aumentum-api.service

# Reload systemd
sudo systemctl daemon-reload

# Enable service to start on boot
sudo systemctl enable plagis-aumentum-api

# Start the service
sudo systemctl start plagis-aumentum-api

# Check status
sudo systemctl status plagis-aumentum-api
```

### 7. Verify Deployment

```bash
# Check service status
sudo systemctl status plagis-aumentum-api

# Check logs
sudo tail -f /var/log/plagis/api.log

# Test API endpoint
curl http://localhost:8001/health

# Test API docs
curl http://localhost:8001/docs
```

## Manual Configuration

### FreeTDS Configuration

Edit `/etc/freetds/freetds.conf`:

```ini
[MSSQL_LRS43_PROD]
    host = 10.10.10.5
    port = 1433
    tds version = 7.4
    client charset = UTF-8
```

### ODBC Configuration

Edit `/etc/odbcinst.ini`:

```ini
[FreeTDS]
Description=FreeTDS Driver for SQL Server
Driver=/usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so
Setup=/usr/lib/x86_64-linux-gnu/odbc/libtdsS.so
UsageCount=1
```

Edit `/etc/odbc.ini`:

```ini
[MSSQL_LRS43_PROD]
Driver = FreeTDS
ServerName = MSSQL_LRS43_PROD
Database = LRS43
```

### Test Database Connection

```bash
# Test FreeTDS connection
tsql -S MSSQL_LRS43_PROD -U sa -P 'Plagis$registry'

# Test ODBC connection
isql -v MSSQL_LRS43_PROD sa 'Plagis$registry'
```

## Service Management

### Start/Stop/Restart Service

```bash
sudo systemctl start plagis-aumentum-api
sudo systemctl stop plagis-aumentum-api
sudo systemctl restart plagis-aumentum-api
```

### View Logs

```bash
# View all logs
sudo journalctl -u plagis-aumentum-api -f

# View application logs
sudo tail -f /var/log/plagis/api.log

# View error logs
sudo tail -f /var/log/plagis/api-error.log
```

### Check Service Status

```bash
sudo systemctl status plagis-aumentum-api
```

## Firewall Configuration

If you need to expose the API externally:

```bash
# Allow port 8001
sudo ufw allow 8001/tcp

# Or for specific IP
sudo ufw allow from 192.168.1.0/24 to any port 8001
```

## Reverse Proxy (Optional)

For production, use Nginx as a reverse proxy:

### Install Nginx

```bash
sudo apt-get install -y nginx
```

### Create Nginx Configuration

```bash
sudo nano /etc/nginx/sites-available/plagis-api
```

Add configuration:

```nginx
server {
    listen 80;
    server_name your-domain.com;

    location / {
        proxy_pass http://127.0.0.1:8001;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}
```

Enable site:

```bash
sudo ln -s /etc/nginx/sites-available/plagis-api /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx
```

## Troubleshooting

### Service Won't Start

1. Check service status:
   ```bash
   sudo systemctl status plagis-aumentum-api
   ```

2. Check logs:
   ```bash
   sudo journalctl -u plagis-aumentum-api -n 50
   ```

3. Verify Python environment:
   ```bash
   sudo -u plagis /opt/plagis_aumentum/venv/bin/python3 --version
   ```

4. Test database connection:
   ```bash
   sudo -u plagis /opt/plagis_aumentum/venv/bin/python3 -c "import pyodbc; print('pyodbc OK')"
   ```

### Database Connection Issues

1. Verify FreeTDS configuration:
   ```bash
   tsql -S MSSQL_LRS43_PROD -U sa -P 'Plagis$registry'
   ```

2. Check ODBC configuration:
   ```bash
   odbcinst -q -d  # List drivers
   odbcinst -q -s  # List data sources
   ```

3. Test ODBC connection:
   ```bash
   isql -v MSSQL_LRS43_PROD sa 'Plagis$registry'
   ```

### Contentstore Not Found

1. Verify mount:
   ```bash
   mountpoint /mnt/aumentum_contentstore
   ls -la /mnt/aumentum_contentstore/contentstore
   ```

2. Check permissions:
   ```bash
   sudo chown -R plagis:plagis /mnt/aumentum_contentstore
   ```

3. Verify environment variable:
   ```bash
   sudo -u plagis env | grep CONTENTSTORE
   ```

### Port Already in Use

If port 8001 is already in use:

```bash
# Find process using port 8001
sudo lsof -i :8001

# Kill the process
sudo kill <PID>

# Or change port in aumentum_api.py
```

## Security Considerations

1. **Firewall**: Only expose necessary ports
2. **Database Credentials**: Store in environment variables or secure vault
3. **File Permissions**: Ensure proper ownership and permissions
4. **SSL/TLS**: Use reverse proxy with SSL for production
5. **Updates**: Keep system and dependencies updated

## Maintenance

### Update Application

```bash
cd /opt/plagis_aumentum
sudo -u plagis git pull
sudo -u plagis venv/bin/pip install -r requirements.txt
sudo systemctl restart plagis-aumentum-api
```

### Clear Cache

```bash
sudo rm -rf /var/cache/plagis/pdfs/*
sudo systemctl restart plagis-aumentum-api
```

### Backup Configuration

```bash
# Backup service configuration
sudo cp /etc/systemd/system/plagis-aumentum-api.service /opt/backups/

# Backup application
sudo tar -czf /opt/backups/plagis-aumentum-$(date +%Y%m%d).tar.gz /opt/plagis_aumentum
```

## Monitoring

### Health Check Endpoint

The API provides a health check endpoint:

```bash
curl http://localhost:8001/health
```

### Set Up Monitoring

Consider using:
- **Prometheus** for metrics
- **Grafana** for visualization
- **Logwatch** for log monitoring
- **Monit** for process monitoring

## Support

For issues or questions:
1. Check logs: `/var/log/plagis/api.log`
2. Review service status: `sudo systemctl status plagis-aumentum-api`
3. Verify configuration files
4. Test database and contentstore connectivity

