# Migration Guide: Moving Backend from Plugin to Standalone

This document provides step-by-step instructions for migrating the Press Zone Backend from the WordPress plugin directory to a standalone deployment.

## Overview

**From:** `domains/dev3.press.zone/public_html/wp-content/plugins/press-zone-backend/`

**To:** `~/press-zone-backend/`

**Deployment:** Podman containers + systemd + nginx reverse proxy

**Zero Downtime:** Yes, using blue-green deployment strategy

---

## Pre-Migration Checklist

- [ ] Backup current database
- [ ] Document current environment variables
- [ ] Note current API endpoint usage
- [ ] Verify DNS is configured for api.press.zone
- [ ] Ensure user 'press' has necessary permissions
- [ ] Test new configuration locally (optional)

---

## Migration Steps

### Phase 1: Preparation (No Downtime)

#### 1. Backup Existing System

```bash
# As user 'press'
cd ~/domains/dev3.press.zone/public_html/wp-content/plugins/press-zone-backend/api

# Backup database
pg_dump -U translate_user -d translate_db -F c -f ~/translate_db_backup_$(date +%Y%m%d).dump

# Backup .env file
cp .env ~/.env.backup

# Backup Redis (optional)
redis-cli SAVE
sudo cp /var/lib/redis/dump.rdb ~/redis_backup_$(date +%Y%m%d).rdb
```

#### 2. Document Current Configuration

```bash
# As user 'press'
# Note down current environment variables
cat ~/domains/dev3.press.zone/public_html/wp-content/plugins/press-zone-backend/api/.env > ~/current-env-backup.txt

# Note current running processes
ps aux | grep -E "(node|npm)" > ~/current-processes.txt

# Note current ports
sudo netstat -tlnp | grep :3000 > ~/current-ports.txt
```

#### 3. Clone and Setup New Location

```bash
# As user 'press'
cd ~

# If not already cloned
git clone git@github.com:avi-ezra/Press.Zone-Works.git

# Create symbolic link
ln -s ~/Press.Zone-Works/press-zone-backend ~/press-zone-backend

cd ~/press-zone-backend/api
```

#### 4. Copy Environment Configuration

```bash
# As user 'press'
# Copy existing .env
cp ~/domains/dev3.press.zone/public_html/wp-content/plugins/press-zone-backend/api/.env \
   ~/press-zone-backend/api/.env

# Verify all variables are present
diff ~/current-env-backup.txt ~/press-zone-backend/api/.env
```

#### 5. Install Dependencies

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

# Install dependencies
npm ci --production

# Generate Prisma client
npx prisma generate

# Build TypeScript
npm run build
```

---

### Phase 2: Deploy New Instance (Parallel to Old)

#### 6. Configure Nginx for New Backend

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

# Install nginx configuration and SSL
./install-nginx.sh
```

This will:
- Configure reverse proxy to port 3000
- Obtain SSL certificate for api.press.zone
- Configure HTTPS redirect

#### 7. Install Systemd Service

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

#### 8. Start New Backend

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

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

# Verify API responds
curl http://localhost:3000/health
```

---

### Phase 3: Cutover (Brief Downtime: ~30 seconds)

#### 9. Stop Old Backend

```bash
# As user 'press'
cd ~/domains/dev3.press.zone/public_html/wp-content/plugins/press-zone-backend/api

# Find and stop old processes
ps aux | grep -E "tsx.*src/(index|worker)" | grep -v grep
# Note the PIDs

# Stop gracefully
kill <API_PID>
kill <WORKER_PID>

# Wait a few seconds for graceful shutdown
sleep 5

# Force kill if still running
pkill -f "tsx watch src/index"
pkill -f "tsx watch src/worker"
```

#### 10. Verify New Backend

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

# Should return: {"status":"ok","timestamp":"..."}

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

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

---

### Phase 4: Post-Migration Verification

#### 11. Functional Testing

```bash
# Test WordPress plugin connection
# Visit your WordPress site and test translation features

# Check API metrics
curl https://api.press.zone/metrics

# Check worker status
podman ps | grep worker

# Verify database connectivity
cd ~/press-zone-backend/api
npx prisma studio  # Opens on port 5555
```

#### 12. Monitor for Issues

```bash
# Watch logs for 5-10 minutes
journalctl --user -u presszone-backend.service -f

# Check for errors
tail -f ~/press-zone-backend/api/logs/error.log

# Monitor system resources
htop
```

#### 13. Update DNS (if needed)

If api.press.zone wasn't previously configured:

```bash
# Verify DNS propagation
dig api.press.zone +short

# Test from multiple locations
# Use: https://www.whatsmydns.net/#A/api.press.zone
```

---

### Phase 5: Cleanup (After Successful Migration)

#### 14. Remove Old Backend Directory

```bash
# As user 'press'
# ONLY after confirming new backend works for at least 24 hours

cd ~/domains/dev3.press.zone/public_html/wp-content/plugins/translate-press-zone
rm -rf backend-app/

# Or move to backup location
mv backend-app/ ~/backend-app-old-backup/
```

#### 15. Update WordPress Plugin Configuration

If the plugin had any references to the backend-app path, update them to use api.press.zone.

#### 16. Setup Monitoring and Backups

```bash
# As user 'press'
# Add cron jobs for backups
crontab -e

# Add:
0 2 * * * $HOME/press-zone-backend/backup/backup.sh >> $HOME/press-zone-backend/backup/backup.log 2>&1
```

---

## Rollback Plan

If issues occur, rollback quickly:

### Quick Rollback (5 minutes)

```bash
# 1. Stop new backend
systemctl --user stop presszone-backend.service

# 2. Start old backend
cd ~/domains/dev3.press.zone/public_html/wp-content/plugins/press-zone-backend/api
npm run dev &
npm run worker &

# 3. Verify old backend responds
curl http://localhost:3000/health

# 4. Remove nginx configuration
sudo rm /etc/nginx/conf.d/api.press.zone.conf
sudo systemctl reload nginx
```

---

## Verification Checklist

After migration, verify:

- [ ] API health endpoint responds: `curl https://api.press.zone/health`
- [ ] WordPress plugin can connect and translate content
- [ ] Database migrations completed successfully
- [ ] Worker processes are running
- [ ] SSL certificate is valid (check browser)
- [ ] Logs show no critical errors
- [ ] Background jobs are processing
- [ ] Webhooks are being delivered
- [ ] Admin panel accessible (if deployed)
- [ ] Systemd service starts on boot
- [ ] Backups are scheduled

---

## Troubleshooting Common Issues

### Issue: Port 3000 Already in Use

```bash
# Find what's using port 3000
sudo lsof -i :3000

# Kill the process
sudo kill -9 <PID>

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

### Issue: Database Connection Failed

```bash
# Check DATABASE_URL in .env
cat ~/press-zone-backend/api/.env | grep DATABASE_URL

# Test database connection
psql -U translate_user -d translate_db -h localhost

# Verify PostgreSQL is running
sudo systemctl status postgresql-15
```

### Issue: SSL Certificate Not Working

```bash
# Check certbot status
sudo certbot certificates

# Verify DNS
dig api.press.zone +short

# Re-run SSL installation
cd /home/press/press-zone-backend/nginx
sudo ./install-nginx.sh
```

### Issue: Worker Not Processing Jobs

```bash
# Check worker container
podman ps | grep worker

# View worker logs
podman logs presszone-worker

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

---

## Migration Timeline

**Estimated Total Time: 2-3 hours**

- Phase 1 (Preparation): 30 minutes
- Phase 2 (Deploy New): 45 minutes
- Phase 3 (Cutover): 5 minutes (actual downtime: ~30 seconds)
- Phase 4 (Verification): 30 minutes
- Phase 5 (Cleanup): 15 minutes (can be done later)

---

## Post-Migration Optimization

### 1. Configure Podman Auto-Updates

```bash
# Enable automatic container updates
podman auto-update --dry-run
```

### 2. Tune Database Connection Pool

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

### 3. Configure Log Rotation

```bash
# Already configured in systemd service
# Logs are automatically rotated by journald
```

### 4. Set Up Monitoring

Consider adding:
- Uptime monitoring (e.g., UptimeRobot)
- Error tracking (e.g., Sentry)
- Performance monitoring (e.g., New Relic)

---

## Support

If you encounter issues during migration:

1. Check logs: `journalctl --user -u presszone-backend.service -n 100`
2. Verify configuration: `cat ~/press-zone-backend/api/.env`
3. Test database: `psql -U translate_user -d translate_db`
4. Check service status: `systemctl --user status presszone-backend.service`

For persistent issues, consult SERVER-SETUP.md or contact support.
