# Docker Deployment Guide

Complete guide for deploying the Kosmi-IRC bridge using Docker.

## Quick Start

```bash
# 1. Edit configuration
nano matterbridge.toml

# 2. Build and run
docker-compose up -d

# 3. View logs
docker-compose logs -f
```

## Prerequisites

- Docker (20.10+)
- Docker Compose (1.29+)
- A Kosmi room URL
- IRC server access

## Step-by-Step Setup

### 1. Configure the Bridge

Edit `matterbridge.toml` and update these settings:

```toml
[kosmi.hyperspaceout]
RoomURL="https://app.kosmi.io/room/@YOUR_ROOM"  # ← Change this
Debug=false

[irc.libera]
Server="irc.libera.chat:6667"  # ← Change to your IRC server
Nick="kosmi-relay"              # ← Change your bot's nickname

[[gateway.inout]]
account="kosmi.hyperspaceout"
channel="main"

[[gateway.inout]]
account="irc.libera"
channel="#your-channel"         # ← Change to your IRC channel
```

### 2. Build the Docker Image

```bash
docker-compose build
```

This will:
- Install Chrome/Chromium in the container
- Build the Matterbridge binary with Kosmi support
- Create an optimized production image

**Build time**: ~5-10 minutes (first time)

### 3. Run the Container

```bash
# Start in detached mode
docker-compose up -d

# Or start with logs visible
docker-compose up
```

### 4. Verify It's Working

```bash
# Check container status
docker-compose ps

# View logs
docker-compose logs -f matterbridge

# Look for these messages:
# INFO Successfully connected to Kosmi via Chrome
# INFO Successfully connected to IRC
# INFO Gateway(s) started successfully
```

### 5. Test Message Relay

1. **Kosmi → IRC**: Send a message in your Kosmi room
   - Should appear in IRC as: `[Kosmi] <username> message`

2. **IRC → Kosmi**: Send a message in your IRC channel
   - Should appear in Kosmi as: `[IRC] <username> message`

## Docker Commands Reference

### Container Management

```bash
# Start the bridge
docker-compose up -d

# Stop the bridge
docker-compose down

# Restart the bridge
docker-compose restart

# View logs
docker-compose logs -f

# View last 100 lines of logs
docker-compose logs --tail=100

# Check container status
docker-compose ps

# Execute commands in running container
docker-compose exec matterbridge sh
```

### Debugging

```bash
# Enable debug logging (edit docker-compose.yml first)
# Set Debug=true in matterbridge.toml, then:
docker-compose restart

# Check Chrome is installed
docker-compose exec matterbridge which chromium

# Check configuration
docker-compose exec matterbridge cat /app/matterbridge.toml

# Test connectivity
docker-compose exec matterbridge ping -c 3 app.kosmi.io
docker-compose exec matterbridge ping -c 3 irc.libera.chat
```

### Updating

```bash
# Pull latest code
git pull

# Rebuild image
docker-compose build --no-cache

# Restart with new image
docker-compose up -d
```

## Configuration Options

### docker-compose.yml

```yaml
services:
  matterbridge:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: kosmi-irc-relay
    restart: unless-stopped
    volumes:
      - ./matterbridge.toml:/app/matterbridge.toml:ro
      - ./logs:/app/logs
    environment:
      - CHROME_BIN=/usr/bin/chromium
      - CHROME_PATH=/usr/bin/chromium
      - TZ=America/New_York  # ← Change to your timezone
    security_opt:
      - seccomp:unconfined  # Required for Chrome
```

### Environment Variables

| Variable | Description | Default |
|----------|-------------|---------|
| `CHROME_BIN` | Path to Chrome binary | `/usr/bin/chromium` |
| `CHROME_PATH` | Chrome executable path | `/usr/bin/chromium` |
| `TZ` | Timezone for logs | `America/New_York` |
| `DEBUG` | Enable debug logging | `0` |

### Volume Mounts

| Host Path | Container Path | Purpose |
|-----------|----------------|---------|
| `./matterbridge.toml` | `/app/matterbridge.toml` | Configuration file (read-only) |
| `./logs` | `/app/logs` | Log files (optional) |

## Troubleshooting

### Container Won't Start

**Check logs**:
```bash
docker-compose logs
```

**Common issues**:
- Configuration file syntax error
- Missing `matterbridge.toml`
- Port already in use

**Solution**:
```bash
# Validate TOML syntax
docker run --rm -v $(pwd)/matterbridge.toml:/config.toml alpine sh -c "apk add --no-cache go && go install github.com/pelletier/go-toml/cmd/tomll@latest && tomll /config.toml"

# Check if file exists
ls -la matterbridge.toml
```

### Chrome/Chromium Not Found

**Symptoms**:
```
ERROR Chrome binary not found
```

**Solution**:
```bash
# Rebuild image
docker-compose build --no-cache

# Verify Chrome is installed
docker-compose run --rm matterbridge which chromium
```

### WebSocket Connection Failed

**Symptoms**:
```
ERROR Failed to connect to Kosmi
ERROR WebSocket connection failed
```

**Solution**:
```bash
# Test network connectivity
docker-compose exec matterbridge ping -c 3 app.kosmi.io

# Check if room URL is correct
docker-compose exec matterbridge cat /app/matterbridge.toml | grep RoomURL

# Enable debug logging
# Edit matterbridge.toml: Debug=true
docker-compose restart
```

### IRC Connection Failed

**Symptoms**:
```
ERROR Failed to connect to IRC
ERROR Connection refused
```

**Solution**:
```bash
# Test IRC connectivity
docker-compose exec matterbridge nc -zv irc.libera.chat 6667

# Check IRC configuration
docker-compose exec matterbridge cat /app/matterbridge.toml | grep -A 10 "\[irc\]"

# Verify nickname isn't already in use
# Try changing Nick in matterbridge.toml
```

### Messages Not Relaying

**Symptoms**:
- Container running
- Both bridges connected
- But messages don't appear

**Solution**:
```bash
# Enable debug logging
# Edit matterbridge.toml: Debug=true
docker-compose restart

# Watch logs for message flow
docker-compose logs -f | grep -E "Received|Sending|Forwarding"

# Verify gateway configuration
docker-compose exec matterbridge cat /app/matterbridge.toml | grep -A 20 "\[\[gateway\]\]"

# Check channel names match exactly
# Kosmi channel should be "main"
# IRC channel should include # (e.g., "#your-channel")
```

### High Memory Usage

**Symptoms**:
- Container using >500MB RAM
- System slowdown

**Solution**:
```bash
# Add memory limits to docker-compose.yml
services:
  matterbridge:
    mem_limit: 512m
    mem_reservation: 256m

# Restart
docker-compose up -d
```

### Permission Denied Errors

**Symptoms**:
```
ERROR Permission denied writing to /app/logs
```

**Solution**:
```bash
# Create logs directory with correct permissions
mkdir -p logs
chmod 777 logs

# Or run container as root (not recommended)
# Edit docker-compose.yml:
# user: root
```

## Production Deployment

### Using Docker Swarm

```bash
# Initialize swarm
docker swarm init

# Deploy stack
docker stack deploy -c docker-compose.yml kosmi-relay

# Check status
docker stack services kosmi-relay

# View logs
docker service logs -f kosmi-relay_matterbridge
```

### Using Kubernetes

Create `kosmi-relay.yaml`:

```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: kosmi-irc-relay
spec:
  replicas: 1
  selector:
    matchLabels:
      app: kosmi-irc-relay
  template:
    metadata:
      labels:
        app: kosmi-irc-relay
    spec:
      containers:
      - name: matterbridge
        image: kosmi-irc-relay:latest
        volumeMounts:
        - name: config
          mountPath: /app/matterbridge.toml
          subPath: matterbridge.toml
        env:
        - name: CHROME_BIN
          value: /usr/bin/chromium
        - name: TZ
          value: America/New_York
        securityContext:
          capabilities:
            add:
            - SYS_ADMIN  # Required for Chrome
      volumes:
      - name: config
        configMap:
          name: matterbridge-config
```

Deploy:
```bash
kubectl create configmap matterbridge-config --from-file=matterbridge.toml
kubectl apply -f kosmi-relay.yaml
```

### Monitoring

#### Health Check

Add to `docker-compose.yml`:

```yaml
services:
  matterbridge:
    healthcheck:
      test: ["CMD", "pgrep", "-f", "matterbridge"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 40s
```

#### Prometheus Metrics

Matterbridge doesn't expose Prometheus metrics by default, but you can monitor:

```bash
# Container metrics
docker stats kosmi-irc-relay

# Log-based monitoring
docker-compose logs -f | grep -E "ERROR|WARN"
```

### Backup and Restore

```bash
# Backup configuration
cp matterbridge.toml matterbridge.toml.backup

# Backup logs
tar -czf logs-$(date +%Y%m%d).tar.gz logs/

# Restore configuration
cp matterbridge.toml.backup matterbridge.toml
docker-compose restart
```

## Security Best Practices

1. **Run as non-root user** (already configured in Dockerfile)
2. **Use read-only configuration mount**
3. **Limit container resources**
4. **Keep Docker images updated**
5. **Use secrets for sensitive data** (e.g., IRC passwords)

### Using Docker Secrets

```bash
# Create secret
echo "your_irc_password" | docker secret create irc_password -

# Update docker-compose.yml
services:
  matterbridge:
    secrets:
      - irc_password

secrets:
  irc_password:
    external: true
```

## Performance Tuning

### Resource Limits

```yaml
services:
  matterbridge:
    deploy:
      resources:
        limits:
          cpus: '1.0'
          memory: 512M
        reservations:
          cpus: '0.5'
          memory: 256M
```

### Chrome Optimization

Add to `docker-compose.yml`:

```yaml
services:
  matterbridge:
    environment:
      - CHROME_FLAGS=--disable-dev-shm-usage --no-sandbox --disable-setuid-sandbox
```

## Next Steps

- ✅ Bridge is running in Docker
- 🔄 Set up monitoring and alerts
- 🔄 Configure log rotation
- 🔄 Set up automatic backups
- 🔄 Add more bridges (Discord, Slack, etc.)

## Getting Help

- Check logs: `docker-compose logs -f`
- Enable debug: Set `Debug=true` in `matterbridge.toml`
- Review `LESSONS_LEARNED.md` for common issues
- Check `QUICK_REFERENCE.md` for troubleshooting tips

## Example: Complete Setup

```bash
# 1. Clone repository
git clone <your-repo> kosmi-irc-relay
cd kosmi-irc-relay

# 2. Edit configuration
nano matterbridge.toml
# Update RoomURL, IRC server, channel

# 3. Build and start
docker-compose up -d

# 4. Watch logs
docker-compose logs -f

# 5. Test by sending messages in both Kosmi and IRC

# 6. If issues, enable debug
nano matterbridge.toml  # Set Debug=true
docker-compose restart
docker-compose logs -f
```

That's it! Your Kosmi-IRC bridge is now running in Docker! 🎉

