# ASF TestArena - Deployment Guide

## ✅ Network Configuration Complete

The docker-compose.yml has been configured with:
- **Internal Network:** `app-network` (for web ↔ database communication)
- **External Network:** `caddy_network` (for Caddy ↔ web communication)

## 🚀 Quick Deployment

### Option 1: Automated Deployment (Recommended)

**Windows (PowerShell):**
```powershell
.\deploy.ps1
```

**Windows (Command Prompt):**
```cmd
start.bat
```

**Linux/Mac:**
```bash
chmod +x deploy.sh
./deploy.sh
```

The deployment script will:
1. ✅ Check Docker and Docker Compose are installed
2. ✅ Verify Docker daemon is running
3. ✅ Create `.env` file if missing
4. ✅ Check/create `caddy_network` if needed
5. ✅ Stop existing containers
6. ✅ Build and start new containers
7. ✅ Verify all services are running
8. ✅ Display access information

### Option 2: Manual Deployment

```bash
# 1. Create .env file (optional)
cp .env.example .env
# Edit .env with your values

# 2. Ensure Caddy network exists
docker network create caddy_network

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

# 4. Check status
docker-compose ps
docker-compose logs -f
```

## 🔧 Configuration

### Environment Variables

The `.env` file (optional) can override these defaults:

```env
DATABASE_URL=postgresql://testarena_user:YOUR_PASSWORD@db:5432/testarena
SECRET_KEY=YOUR_SECURE_SECRET_KEY
FLASK_ENV=production
```

**Generate a secure SECRET_KEY:**

**Python:**
```bash
python -c "import secrets; print(secrets.token_hex(32))"
```

**PowerShell:**
```powershell
-join ((48..57) + (65..90) + (97..122) | Get-Random -Count 64 | % {[char]$_})
```

**Linux:**
```bash
openssl rand -hex 32
```

### Database Password

Update in `docker-compose.yml`:
```yaml
environment:
  POSTGRES_PASSWORD: YOUR_SECURE_PASSWORD
  DATABASE_URL: postgresql://testarena_user:YOUR_SECURE_PASSWORD@db:5432/testarena
```

## 🌐 Caddy Configuration

Add this to your Caddyfile:

```
testarena.nabd-co.com {
    reverse_proxy testarena_web:5000
    
    encode gzip
    
    header {
        Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
        X-Frame-Options "SAMEORIGIN"
        X-Content-Type-Options "nosniff"
        X-XSS-Protection "1; mode=block"
    }
    
    log {
        output file /var/log/caddy/testarena.log
        format json
    }
}
```

Reload Caddy:
```bash
docker exec caddy_container caddy reload --config /etc/caddy/Caddyfile
```

## ✅ Verification

### 1. Check Containers
```bash
docker-compose ps
```

Expected output:
```
Name                 Command              State    Ports
----------------------------------------------------------
testarena_db    docker-entrypoint.sh postgres   Up      5432/tcp
testarena_web   gunicorn --bind 0.0.0.0:5000... Up      5000/tcp
```

### 2. Check Logs
```bash
# All logs
docker-compose logs

# Follow logs
docker-compose logs -f

# Specific service
docker-compose logs web
docker-compose logs db
```

### 3. Check Networks
```bash
# Verify web container is on both networks
docker inspect testarena_web | grep -A 10 Networks
```

Should show both `app-network` and `caddy_network`.

### 4. Test Access

**Local:**
```bash
curl http://localhost:5000
```

**Domain:**
```bash
curl https://testarena.nabd-co.com
```

### 5. Test Login

1. Open browser: https://testarena.nabd-co.com
2. Login with:
   - Username: `admin`
   - Password: `admin123`
3. **Change password immediately!**

## 🔐 Post-Deployment Security

### 1. Change Admin Password
1. Login as admin
2. Go to Admin Dashboard
3. Reset admin password

### 2. Update Secrets
```bash
# Edit docker-compose.yml
nano docker-compose.yml

# Update:
# - SECRET_KEY
# - POSTGRES_PASSWORD
# - DATABASE_URL password

# Restart
docker-compose down
docker-compose up -d
```

### 3. Create Users
1. Login as admin
2. Go to Admin Dashboard
3. Create user accounts for your team

## 📊 Monitoring

### View Logs
```bash
# Real-time logs
docker-compose logs -f

# Last 100 lines
docker-compose logs --tail=100

# Specific service
docker-compose logs -f web
```

### Check Resource Usage
```bash
docker stats testarena_web testarena_db
```

### Database Backup
```bash
# Create backup
docker exec testarena_db pg_dump -U testarena_user testarena > backup_$(date +%Y%m%d).sql

# Restore backup
docker exec -i testarena_db psql -U testarena_user testarena < backup_20241128.sql
```

## 🛠️ Maintenance

### Restart Services
```bash
# Restart all
docker-compose restart

# Restart specific service
docker-compose restart web
docker-compose restart db
```

### Update Application
```bash
# Pull latest changes
git pull

# Rebuild and restart
docker-compose up -d --build
```

### Stop Services
```bash
# Stop containers (keep data)
docker-compose down

# Stop and remove volumes (DELETE DATA!)
docker-compose down -v
```

### View Container Shell
```bash
# Web container
docker exec -it testarena_web bash

# Database container
docker exec -it testarena_db psql -U testarena_user testarena
```

## 🐛 Troubleshooting

### Container Won't Start

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

**Common issues:**
- Database not ready: Wait 30 seconds
- Port conflict: Check if port 5000 is in use
- Network issue: Verify `caddy_network` exists

### Database Connection Error

**Check DATABASE_URL:**
```bash
docker-compose exec web env | grep DATABASE_URL
```

**Test connection:**
```bash
docker-compose exec web python -c "from app import create_app, db; app = create_app(); app.app_context().push(); print('DB OK')"
```

### Can't Access via Domain

**Check Caddy:**
```bash
docker logs caddy_container_name
```

**Check network:**
```bash
docker network inspect caddy_network
```

Should show `testarena_web` in containers list.

**Check DNS:**
```bash
nslookup testarena.nabd-co.com
```

### 502 Bad Gateway

**Wait for initialization:**
```bash
# Web container may still be starting
sleep 10
curl http://localhost:5000
```

**Check web container:**
```bash
docker-compose logs web
docker exec testarena_web ps aux | grep gunicorn
```

## 📋 Deployment Checklist

- [ ] Docker and Docker Compose installed
- [ ] Docker daemon running
- [ ] Caddy network exists (`docker network ls`)
- [ ] `.env` file configured (optional)
- [ ] Secrets updated in docker-compose.yml
- [ ] Caddyfile configured
- [ ] DNS pointing to server
- [ ] Deployment script executed
- [ ] Containers running (`docker-compose ps`)
- [ ] No errors in logs (`docker-compose logs`)
- [ ] Login page accessible
- [ ] Admin login works
- [ ] Admin password changed
- [ ] Test users created
- [ ] All features tested

## 🎉 Success!

If all checks pass, your ASF TestArena is now running!

**Access URLs:**
- Local: http://localhost:5000
- Domain: https://testarena.nabd-co.com

**Default Credentials:**
- Username: `admin`
- Password: `admin123`

**⚠️ CHANGE THE PASSWORD IMMEDIATELY!**

## 📞 Need Help?

- Check logs: `docker-compose logs -f`
- Review: [TROUBLESHOOTING.md](TROUBLESHOOTING.md)
- Read: [START_HERE.md](START_HERE.md)
- Index: [INDEX.md](INDEX.md)

## 🚀 Next Steps

1. Change admin password
2. Create user accounts
3. Test job submission workflow
4. Set up automated backups
5. Configure monitoring
6. Plan Phase 2 implementation

---

**Deployment Date:** _______________  
**Deployed By:** _______________  
**Server:** _______________  
**Domain:** testarena.nabd-co.com
