# Press Zone Backend - Server Setup Guide

This document provides complete instructions for deploying the Press Zone Backend on a production server.

## Table of Contents

1. [Server Requirements](#server-requirements)
2. [Initial Server Setup](#initial-server-setup)
3. [Installing Dependencies](#installing-dependencies)
4. [Deploying the Backend](#deploying-the-backend)
5. [Configuring SSL](#configuring-ssl)
6. [Setting Up Monitoring](#setting-up-monitoring)
7. [Maintenance](#maintenance)
8. [Troubleshooting](#troubleshooting)

---

## Server Requirements

### Minimum Specifications
- **OS**: Rocky Linux 8+ / AlmaLinux 8+ / RHEL 8+
- **CPU**: 4 cores
- **RAM**: 8GB
- **Storage**: 50GB SSD
- **Network**: Public IP with DNS configured

### Required Services
- PostgreSQL 15+
- Redis 7+
- Podman 4.0+
- Node.js 20+
- Nginx
- Git

### DNS Configuration
Before starting, ensure DNS is configured:
- `api.press.zone` → Server IP
- Port 80/443 open for SSL certificate

---

## Initial Server Setup

### 1. Create User 'press'

```bash
# As root
useradd -m -s /bin/bash press
usermod -aG wheel press  # Add to sudo group
passwd press  # Set password
```

### 2. Configure SSH Access

```bash
# As root
su - press
mkdir -p ~/.ssh
chmod 700 ~/.ssh

# Copy your public key
echo "your-ssh-public-key-here" >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys
```

### 3. Enable User Lingering

This allows user services to run when not logged in:

```bash
# As root
loginctl enable-linger press
```

---

## Installing Dependencies

### 1. Install System Packages

```bash
# As root
dnf update -y

# Install PostgreSQL 15
dnf install -y postgresql15-server postgresql15-contrib
postgresql-15-setup initdb
systemctl enable --now postgresql-15

# Install Redis
dnf install -y redis
systemctl enable --now redis

# Install Podman
dnf install -y podman podman-compose

# Install Node.js 20
dnf module install -y nodejs:20/common

# Install Nginx
dnf install -y nginx
systemctl enable --now nginx

# Install Certbot for SSL
dnf install -y certbot python3-certbot-nginx

# Install Git
dnf install -y git
```

### 2. Configure PostgreSQL

```bash
# As root, switch to postgres user
su - postgres

# Create database and user
createuser translate_user
createdb -O translate_user translate_db
psql -c "ALTER USER translate_user WITH PASSWORD 'your-secure-password-here';"

# Configure pg_hba.conf for local connections
echo "local   translate_db   translate_user   md5" >> /var/lib/pgsql/15/data/pg_hba.conf

# Reload PostgreSQL
systemctl reload postgresql-15
```

### 3. Configure Redis

```bash
# As root
# Redis should work out of the box for local connections
systemctl status redis
```

### 4. Configure Firewall

```bash
# As root
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload
```

---

## Deploying the Backend

### 1. Clone Repository

```bash
# As user 'press'
cd ~
git clone git@github.com:avi-ezra/Press.Zone-Works.git
cd Press.Zone-Works
```

### 2. Create Symbolic Link (Optional but Recommended)

```bash
# As user 'press'
ln -s ~/Press.Zone-Works/press-zone-backend ~/press-zone-backend
cd ~/press-zone-backend
```

### 3. Configure Environment Variables

```bash
# As user 'press'
cd ~/press-zone-backend/api

# Copy example file
cp .env.example .env

# Edit with production values
nano .env
```

**Required Environment Variables:**

```bash
NODE_ENV=production
PORT=3000

# Database
DATABASE_URL=postgresql://translate_user:your-password@localhost:5432/translate_db?schema=public

# Redis
REDIS_HOST=localhost
REDIS_PORT=6379

# JWT Secrets (generate with: openssl rand -hex 32)
JWT_SECRET=your-64-char-random-string
JWT_ACCESS_SECRET=your-64-char-random-string
JWT_REFRESH_SECRET=your-64-char-random-string

# Google AI (for translations)
GOOGLE_API_KEY=your-google-api-key

# Google Gemini API (Translation Engine)
GEMINI_API_KEY=your-google-gemini-api-key
GEMINI_MODEL=gemini-3-flash-preview

# PayPal
PAYPAL_CLIENT_ID=your-paypal-client-id
PAYPAL_CLIENT_SECRET=your-paypal-secret
PAYPAL_MODE=live

# URLs
CORS_ALLOWED_ORIGINS=https://admin.translate.press.zone,https://translate.press.zone
API_URL=https://api.press.zone
FRONTEND_URL=https://translate.press.zone
ADMIN_PANEL_URL=https://admin.translate.press.zone
```

### 4. Install Dependencies and Build

```bash
# As user 'press'
cd ~/press-zone-backend/api

# Install dependencies
npm ci --production

# Generate Prisma client
npx prisma generate

# Run database migrations
npx prisma migrate deploy

# Build TypeScript
npm run build
```

### 5. Install Systemd Service

```bash
# As user 'press'
cd ~/press-zone-backend/systemd
./install-systemd.sh
```

### 6. Start Services

```bash
# As user 'press'
systemctl --user start presszone-backend.service
systemctl --user status presszone-backend.service

# Check if API is responding
curl http://localhost:3000/health
```

---

## Configuring SSL

### 1. Install Nginx Configuration

```bash
# As root
cd /home/press/press-zone-backend/nginx
./install-nginx.sh
```

This script will:
- Install nginx configuration
- Obtain SSL certificate from Let's Encrypt
- Configure auto-renewal
- Set up HTTPS with modern security settings

### 2. Verify SSL

```bash
# Test from external machine
curl https://api.press.zone/health

# Check SSL grade
# Visit: https://www.ssllabs.com/ssltest/analyze.html?d=api.press.zone
```

---

## Setting Up Monitoring

### 1. Configure Automatic Backups

```bash
# As user 'press'
crontab -e

# Add these lines:
0 2 * * * $HOME/press-zone-backend/backup/backup.sh >> $HOME/press-zone-backend/backup/backup.log 2>&1
0 3 * * 0 find $HOME/press-zone-backend/api/logs -name "*.log" -mtime +30 -delete
```

### 2. View Logs

```bash
# Service logs
journalctl --user -u presszone-backend.service -f

# Application logs
tail -f ~/press-zone-backend/api/logs/combined.log
tail -f ~/press-zone-backend/api/logs/error.log

# Nginx logs
sudo tail -f /var/log/nginx/api.press.zone.access.log
sudo tail -f /var/log/nginx/api.press.zone.error.log
```

### 3. Health Monitoring

```bash
# API health endpoint
curl https://api.press.zone/health

# Check running containers
podman ps

# Check service status
systemctl --user status presszone-backend.service
```

---

## Maintenance

### Updating the Backend

```bash
# As user 'press'
cd ~/press-zone-backend
./update.sh  # Quick restart

# OR for full deployment with migrations
./deploy.sh
```

### Manual Service Management

```bash
# As user 'press'
systemctl --user start presszone-backend      # Start
systemctl --user stop presszone-backend       # Stop
systemctl --user restart presszone-backend    # Restart
systemctl --user status presszone-backend     # Status
```

### Database Backup

```bash
# As user 'press'
cd ~/press-zone-backend/backup
./backup.sh
```

### Database Restore

```bash
# As user 'press'
cd ~/press-zone-backend/backup
./restore.sh backup/postgres_20240126_020000.dump.gz
```

---

## Troubleshooting

### API Not Responding

```bash
# Check service status
systemctl --user status presszone-backend.service

# Check logs
journalctl --user -u presszone-backend.service -n 100

# Check if containers are running
podman ps

# Restart services
systemctl --user restart presszone-backend.service
```

### Database Connection Issues

```bash
# Test PostgreSQL connection
psql -U translate_user -d translate_db -h localhost

# Check PostgreSQL status
sudo systemctl status postgresql-15

# View PostgreSQL logs
sudo tail -f /var/lib/pgsql/15/data/log/postgresql-*.log
```

### Redis Connection Issues

```bash
# Test Redis connection
redis-cli ping

# Check Redis status
sudo systemctl status redis

# View Redis logs
sudo journalctl -u redis -n 100
```

### SSL Certificate Issues

```bash
# Check certificate status
sudo certbot certificates

# Renew certificate manually
sudo certbot renew

# Test nginx configuration
sudo nginx -t
```

### Port 3000 Already in Use

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

# Kill old process
sudo kill -9 <PID>

# Restart services
systemctl --user restart presszone-backend.service
```

### Permission Issues

```bash
# Fix ownership of press-zone-backend directory
sudo chown -R press:press ~/press-zone-backend

# Fix permissions
chmod +x ~/press-zone-backend/*.sh
chmod +x ~/press-zone-backend/backup/*.sh
```

---

## Security Checklist

- [ ] PostgreSQL password is strong and unique
- [ ] JWT secrets are randomly generated (64+ characters)
- [ ] .env file permissions are restricted (`chmod 600`)
- [ ] Firewall is configured (only 80/443 open)
- [ ] SSL certificate is valid and auto-renewing
- [ ] Automatic backups are scheduled
- [ ] SELinux/AppArmor is enabled (if applicable)
- [ ] Regular security updates scheduled
- [ ] Monitoring and alerting configured

---

## Performance Tuning

### PostgreSQL

```sql
-- Increase connection pool (in postgresql.conf)
max_connections = 100
shared_buffers = 2GB
effective_cache_size = 6GB
```

### Redis

```bash
# In /etc/redis.conf
maxmemory 512mb
maxmemory-policy allkeys-lru
```

### Node.js

```bash
# In .env
DATABASE_POOL_SIZE=20
```

---

## Support

For issues or questions:
- **GitHub Issues**: https://github.com/avi-ezra/Press.Zone-Works/issues
- **Documentation**: https://docs.press.zone
- **Email**: admin@press.zone
