# PostgreSQL Ubuntu Server Deployment Guide

## Overview

This guide will help you deploy the Church Song Lyric application to your Ubuntu server at **192.168.10.130** using **PostgreSQL** database on port **5100**.

## Prerequisites

- Ubuntu Server 20.04+ at 192.168.10.130 with sudo access
- SSH access configured
- Minimum 2GB RAM, 2 CPU cores, 20GB disk space

---

## Step 1: Connect to Ubuntu Server

From your Windows machine:

```powershell
ssh username@192.168.10.130
```

---

## Step 2: Install PostgreSQL

```bash
# Update system
sudo apt update && sudo apt upgrade -y

# Install PostgreSQL
sudo apt install postgresql postgresql-contrib -y

# Start and enable PostgreSQL
sudo systemctl start postgresql
sudo systemctl enable postgresql

# Check status
sudo systemctl status postgresql
```

---

## Step 3: Create PostgreSQL Database and User

```bash
# Switch to postgres user
sudo -u postgres psql

# In PostgreSQL prompt, run these commands:
CREATE DATABASE church_songlyric;
CREATE USER songlyric_user WITH ENCRYPTED PASSWORD 'your_secure_password_here';
GRANT ALL PRIVILEGES ON DATABASE church_songlyric TO songlyric_user;

# For PostgreSQL 15+, also grant schema privileges:
\c church_songlyric
GRANT ALL ON SCHEMA public TO songlyric_user;
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO songlyric_user;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO songlyric_user;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO songlyric_user;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO songlyric_user;

# Exit psql
\q
```

---

## Step 4: Configure PostgreSQL for Network Access

```bash
# Edit PostgreSQL configuration
sudo nano /etc/postgresql/*/main/postgresql.conf

# Find and uncomment/modify this line:
listen_addresses = '*'

# Save and exit (Ctrl+X, Y, Enter)

# Edit pg_hba.conf to allow connections
sudo nano /etc/postgresql/*/main/pg_hba.conf

# Add this line at the end:
host    church_songlyric    songlyric_user    192.168.10.0/24    md5

# Save and exit

# Restart PostgreSQL
sudo systemctl restart postgresql
```

---

## Step 5: Transfer Project Files

From your Windows machine (PowerShell):

```powershell
# Transfer entire project
scp -r "E:\Documents\Website Projects\Church_SongLyric" username@192.168.10.130:/tmp/

# Or use WinSCP/FileZilla
```

---

## Step 6: Setup Project on Ubuntu

SSH to the server and run:

```bash
# Move project to installation directory
sudo mkdir -p /var/www
sudo mv /tmp/Church_SongLyric /var/www/church-songlyric
cd /var/www/church-songlyric

# Set ownership
sudo chown -R $USER:www-data .
sudo chmod -R 755 .

# Make scripts executable
chmod +x *.sh
```

---

## Step 7: Install System Dependencies

```bash
sudo apt install -y \
    python3 \
    python3-pip \
    python3-venv \
    python3-dev \
    libpq-dev \
    nodejs \
    npm \
    nginx \
    git \
    curl \
    ufw \
    tesseract-ocr \
    poppler-utils \
    libtesseract-dev \
    libleptonica-dev
```

---

## Step 8: Setup Backend

```bash
cd /var/www/church-songlyric/backend

# Create virtual environment
python3 -m venv venv

# Activate virtual environment
source venv/bin/activate

# Upgrade pip
pip install --upgrade pip

# Install Python dependencies
pip install -r requirements.txt

# Create .env file
nano .env
```

Add this to `.env`:

```env
# PostgreSQL connection
POSTGRESQL_URI=postgresql://songlyric_user:your_secure_password_here@192.168.10.130:5432/church_songlyric

# Flask configuration
FLASK_PORT=5100
FLASK_ENV=production
SECRET_KEY=change-this-to-a-random-secret-key-min-32-chars

# Allowed origins
ALLOWED_ORIGINS=http://192.168.10.130,http://192.168.10.178:3000

# Optional API tokens
GENIUS_TOKEN=your_genius_token_if_needed
```

Save and exit (Ctrl+X, Y, Enter)

---

## Step 9: Migrate Data to PostgreSQL

```bash
# Still in backend folder with venv activated
cd /var/www/church-songlyric/backend
source venv/bin/activate

# Run migration script
python migrate_to_postgresql.py

# This will migrate data from data.json to PostgreSQL
```

---

## Step 10: Test Backend

```bash
# Test the backend
python app.py

# Should show:
# * Running on http://0.0.0.0:5100

# Open another terminal and test:
curl http://192.168.10.130:5100/api/health

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

# Stop the test server (Ctrl+C)
```

---

## Step 11: Setup Frontend

```bash
cd /var/www/church-songlyric/frontend

# Install dependencies
npm install

# Update .env.production
nano .env.production
```

Add:

```env
REACT_APP_API_URL=http://192.168.10.130/api
GENERATE_SOURCEMAP=false
```

Save and build:

```bash
npm run build
```

---

## Step 12: Create Systemd Service

```bash
sudo nano /etc/systemd/system/church-songlyric-backend.service
```

Paste:

```ini
[Unit]
Description=Church Song Lyric Backend (Flask)
After=network.target postgresql.service

[Service]
Type=simple
User=www-data
Group=www-data
WorkingDirectory=/var/www/church-songlyric/backend
Environment="PATH=/var/www/church-songlyric/backend/venv/bin"
ExecStart=/var/www/church-songlyric/backend/venv/bin/python app.py
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
```

Save and enable:

```bash
sudo systemctl daemon-reload
sudo systemctl enable church-songlyric-backend
sudo systemctl start church-songlyric-backend
sudo systemctl status church-songlyric-backend
```

---

## Step 13: Configure Nginx

```bash
sudo nano /etc/nginx/sites-available/church-songlyric
```

Paste:

```nginx
server {
    listen 80;
    server_name 192.168.10.130;

    # Serve React frontend
    root /var/www/church-songlyric/frontend/build;
    index index.html;

    # Frontend routing
    location / {
        try_files $uri $uri/ /index.html;
    }

    # Proxy API requests to Flask backend
    location /api {
        proxy_pass http://localhost:5100;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        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;
        
        # Increase timeouts
        proxy_connect_timeout 600;
        proxy_send_timeout 600;
        proxy_read_timeout 600;
        send_timeout 600;
    }

    # Static file caching
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }

    client_max_body_size 50M;
}
```

Enable and restart:

```bash
sudo ln -sf /etc/nginx/sites-available/church-songlyric /etc/nginx/sites-enabled/
sudo rm -f /etc/nginx/sites-enabled/default
sudo nginx -t
sudo systemctl restart nginx
```

---

## Step 14: Configure Firewall

```bash
sudo ufw allow OpenSSH
sudo ufw allow 'Nginx Full'
sudo ufw allow 5432/tcp  # PostgreSQL
sudo ufw enable
sudo ufw status
```

---

## Step 15: Verify Deployment

### Check services

```bash
sudo systemctl status church-songlyric-backend
sudo systemctl status nginx
sudo systemctl status postgresql
```

### Test API

```bash
curl http://192.168.10.130/api/health
```

### Access from browser

Open: `http://192.168.10.130`

---

## Troubleshooting

### Backend won't start

```bash
sudo journalctl -u church-songlyric-backend -n 50 --no-pager
```

### PostgreSQL connection issues

```bash
# Test connection
psql -h 192.168.10.130 -U songlyric_user -d church_songlyric

# Check if PostgreSQL is listening
sudo netstat -tulpn | grep 5432
```

### Port conflicts

```bash
# Check if port 5100 is in use
sudo netstat -tulpn | grep 5100
```

### Permission errors

```bash
sudo chown -R www-data:www-data /var/www/church-songlyric
```

---

## Management Commands

```bash
# Service management
sudo systemctl start church-songlyric-backend
sudo systemctl stop church-songlyric-backend
sudo systemctl restart church-songlyric-backend
sudo systemctl status church-songlyric-backend

# View logs
sudo journalctl -u church-songlyric-backend -f

# PostgreSQL management
sudo -u postgres psql
\c church_songlyric
\dt  # List tables
SELECT * FROM songs LIMIT 5;
```

---

## Backup PostgreSQL Database

```bash
# Backup
pg_dump -h 192.168.10.130 -U songlyric_user -d church_songlyric > backup.sql

# Restore
psql -h 192.168.10.130 -U songlyric_user -d church_songlyric < backup.sql
```

---

## Update Application

```bash
# Transfer new files via SCP
# Then on server:

cd /var/www/church-songlyric

# Update backend
cd backend
source venv/bin/activate
pip install -r requirements.txt
sudo systemctl restart church-songlyric-backend

# Update frontend
cd ../frontend
npm install
npm run build
sudo systemctl reload nginx
```

---

## Success! 🎉

Your Church Song Lyric application is now running on:

- **URL**: <http://192.168.10.130>
- **API**: <http://192.168.10.130/api>
- **Port**: 5100 (backend)
- **Database**: PostgreSQL on 192.168.10.130:5432
