# 🥑 TheKetoBay — VPS Deployment Guide (SSH)

Ovaj guide vodi te korak po korak od praznog VPS-a do live theketobay.com.

---

## 📋 Što ti treba

| Stvar | Detalji |
|-------|---------|
| **VPS** | Ubuntu 22.04 LTS, min. 8GB RAM (16GB za llama3:8b) |
| **Domena** | theketobay.com → DNS A record → IP servera |
| **Stripe account** | stripe.com → API keys |
| **Telegram bot token** | @BotFather na Telegramu |
| **Email/SMTP** | Vlastiti mail server ili Brevo/Mailgun besplatni tier |
| **SSH pristup** | root ili sudo user |

---

## 🔌 STEP 1 — Povežite se na VPS

```bash
ssh root@YOUR_SERVER_IP
# ili ako imate SSH key:
ssh -i ~/.ssh/id_rsa root@YOUR_SERVER_IP
```

---

## 🖥️ STEP 2 — Priprema servera

Kopirajte i pokrenite jednu po jednu naredbu:

```bash
# Update sistema
apt-get update && apt-get upgrade -y

# Instalirajte Docker
curl -fsSL https://get.docker.com | sh
systemctl enable docker && systemctl start docker

# Docker Compose v2 alias
ln -sf /usr/libexec/docker/cli-plugins/docker-compose /usr/local/bin/docker-compose

# Instalirajte Node.js 20
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
apt-get install -y nodejs

# Instalirajte Git, Unzip, ostale alate
apt-get install -y git unzip nano htop ufw fail2ban

# Provjera
docker --version && node --version && npm --version
```

---

## 📂 STEP 3 — Upload fajlova na VPS

### Opcija A — SCP (direktno sa lokalnog računala)

```bash
# Na LOKALNOM računalu (ne na serveru):
scp theketobay_project.zip root@YOUR_SERVER_IP:/var/www/

# Zatim na serveru:
ssh root@YOUR_SERVER_IP
cd /var/www
unzip theketobay_project.zip
mv theketobay /var/www/theketobay
```

### Opcija B — rsync (ako imaš SSH key, brže)

```bash
# Na LOKALNOM računalu:
rsync -avz --progress theketobay/ root@YOUR_SERVER_IP:/var/www/theketobay/
```

### Opcija C — Git (ako koristiš GitHub/GitLab)

```bash
# Na serveru:
mkdir -p /var/www/theketobay
cd /var/www
git clone https://github.com/YOUR_USERNAME/theketobay.git
cd theketobay
```

---

## ⚙️ STEP 4 — Konfiguracija .env

```bash
cd /var/www/theketobay
cp .env.example .env
nano .env
```

### Što MORATE popuniti:

```env
# ── PROMIJENI OVO ─────────────────────────────────
NODE_ENV=production
FRONTEND_URL=https://theketobay.com
NEXT_PUBLIC_SITE_URL=https://theketobay.com

# Database (odaberi jake lozinke)
POSTGRES_PASSWORD=UpisiBaremOvdjeJakuLozinkuXYZ123

# JWT (generiraj: openssl rand -base64 64)
JWT_SECRET=GENERIRAJ_OVU_VRIJEDNOST_openssl_rand_base64_64

# Stripe (stripe.com → Developers → API Keys)
STRIPE_SECRET_KEY=sk_live_...
STRIPE_WEBHOOK_SECRET=whsec_...
STRIPE_PRICE_BASIC=price_...
STRIPE_PRICE_PRO=price_...
STRIPE_PRICE_LIFETIME=price_...

# Telegram (@BotFather → /newbot)
TELEGRAM_BOT_TOKEN=1234567890:ABCdef...

# Email (vlastiti server ili Brevo besplatno)
SMTP_HOST=smtp.brevo.com
SMTP_PORT=587
SMTP_USER=tvoj@email.com
SMTP_PASS=tvoja_lozinka
```

### Generiraj sigurne vrijednosti:

```bash
# JWT Secret:
openssl rand -base64 64

# DB Password:
openssl rand -base64 24 | tr -d '/+='

# Redis Password:
openssl rand -base64 16 | tr -d '/+='
```

---

## 🚀 STEP 5 — DNS Konfiguracija

U DNS provideru (Cloudflare, Namecheap, itd.) postavi:

```
A     theketobay.com      →  YOUR_SERVER_IP    TTL: 300
A     www.theketobay.com  →  YOUR_SERVER_IP    TTL: 300
```

**Provjeri DNS propagaciju:**
```bash
# Na serveru:
nslookup theketobay.com
# Treba pokazati tvoj IP
```

---

## 🐳 STEP 6 — Pokretanje Stack-a

```bash
cd /var/www/theketobay

# Napravi potrebne direktorije
mkdir -p infrastructure/db-backup
mkdir -p infrastructure/nginx/conf.d

# Pokreni infrastrukturu (DB, Redis, Ollama, MinIO)
docker compose -f infrastructure/docker-compose.yml up postgres redis minio ollama -d

# Čekaj da baza bude gotova (10-15 sec)
sleep 15

# Provjeri da radi
docker exec ketobay_db pg_isready -U ketobay
```

---

## 🗄️ STEP 7 — Database Setup

```bash
cd /var/www/theketobay

# Instaliraj npm dependencies
npm install

# Generiraj Prisma client
npx prisma generate --schema=packages/db/prisma/schema.prisma

# Kreiraj tablice u bazi
npx prisma db push --schema=packages/db/prisma/schema.prisma

# Seed početnih podataka (planovi, produkti, blog, achievementi, kuponi)
cd packages/db && npx tsx prisma/seed.ts
cd /var/www/theketobay
```

**Provjeri bazu:**
```bash
docker exec -it ketobay_db psql -U ketobay -c "\dt"
# Treba prikazati sve tablice: users, keto_plans, products, itd.
```

---

## 🔒 STEP 8 — SSL Certifikat (Let's Encrypt)

```bash
cd /var/www/theketobay

# Prvo pokreni nginx samo na HTTP (za ACME challenge)
docker run -d --name nginx_temp \
  -p 80:80 \
  nginx:alpine

sleep 3

# Dohvati certifikat
docker run --rm \
  -v /var/www/theketobay/infrastructure/certbot/conf:/etc/letsencrypt \
  -v /var/www/theketobay/infrastructure/certbot/www:/var/www/certbot \
  certbot/certbot certonly \
  --standalone \
  -d theketobay.com \
  -d www.theketobay.com \
  --email tvoj@email.com \
  --agree-tos \
  --no-eff-email

# Zaustavi temp nginx
docker stop nginx_temp && docker rm nginx_temp
```

**Provjeri certifikat:**
```bash
ls /var/www/theketobay/infrastructure/certbot/conf/live/theketobay.com/
# Treba biti: fullchain.pem, privkey.pem
```

---

## 🏗️ STEP 9 — Build & Start Aplikacije

```bash
cd /var/www/theketobay

# Build svih aplikacija
npm run build

# Ili build s Dockerom (sporije ali pouzdanije):
docker compose -f infrastructure/docker-compose.yml build api web bot

# Pokreni sve servise
docker compose -f infrastructure/docker-compose.yml up -d

# Provjeri status
docker compose -f infrastructure/docker-compose.yml ps
```

Treba prikazati sve servise kao **running**:
```
NAME                STATUS
ketobay_postgres    Up
ketobay_redis       Up
ketobay_ollama      Up
ketobay_minio       Up
ketobay_api         Up
ketobay_web         Up
ketobay_bot         Up
ketobay_nginx       Up
```

---

## 🤖 STEP 10 — Ollama AI Model

```bash
# Provjeri koji model je u .env
grep OLLAMA_MODEL /var/www/theketobay/.env

# Pull model (može trajati 5-30 min ovisno o brzini interneta)
docker exec ketobay_ollama ollama pull llama3:8b

# Ili lakši model (4GB RAM vs 8GB):
docker exec ketobay_ollama ollama pull mistral:7b

# Provjeri
docker exec ketobay_ollama ollama list
```

**Preporuke po RAM-u:**
| RAM servera | Model | Veličina |
|-------------|-------|---------|
| 8 GB | `mistral:7b` | 4.1 GB |
| 16 GB | `llama3:8b` | 4.7 GB ✅ |
| 32 GB+ | `llama3:70b` | 40 GB |

---

## 🎯 STEP 11 — Stripe Webhook

1. Idi na [dashboard.stripe.com](https://dashboard.stripe.com)
2. Developers → Webhooks → **Add endpoint**
3. URL: `https://theketobay.com/api/payments/webhook`
4. Events: odaberi sve `checkout.session.*` i `customer.subscription.*`
5. Kopiraj **Signing secret** u `.env` → `STRIPE_WEBHOOK_SECRET`
6. Restart API: `docker restart ketobay_api`

---

## ⚙️ STEP 12 — Auto-Start na Reboot

```bash
# Systemd service
cat > /etc/systemd/system/theketobay.service << 'EOF'
[Unit]
Description=TheKetoBay Stack
Requires=docker.service
After=docker.service network-online.target

[Service]
Type=oneshot
RemainAfterExit=yes
WorkingDirectory=/var/www/theketobay
ExecStart=/usr/bin/docker compose -f infrastructure/docker-compose.yml up -d
ExecStop=/usr/bin/docker compose -f infrastructure/docker-compose.yml down

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable theketobay
```

**SSL Auto-Renewal (cron):**
```bash
crontab -e
# Dodaj liniju:
0 3 * * * docker exec ketobay_certbot certbot renew --quiet && docker exec ketobay_nginx nginx -s reload
```

---

## ✅ STEP 13 — Provjera

```bash
# Health check API
curl https://theketobay.com/api/health

# Test Ollama
curl http://localhost:11434/api/tags

# Provjeri logove
docker compose -f /var/www/theketobay/infrastructure/docker-compose.yml logs --tail=50 api

# Admin login
# URL:      https://theketobay.com/admin
# Email:    admin@theketobay.com
# Password: Admin123!  ← ODMAH PROMIJENI!
```

---

## 🔧 KORISNE NAREDBE

```bash
# Sve naredbe pokreći iz: /var/www/theketobay
cd /var/www/theketobay

# ── Status servisa ─────────────────────────────
docker compose -f infrastructure/docker-compose.yml ps

# ── Logovi (live) ──────────────────────────────
docker compose -f infrastructure/docker-compose.yml logs -f
docker compose -f infrastructure/docker-compose.yml logs -f api
docker compose -f infrastructure/docker-compose.yml logs -f web

# ── Restart pojedinog servisa ──────────────────
docker restart ketobay_api
docker restart ketobay_web
docker restart ketobay_nginx

# ── Restart svega ──────────────────────────────
docker compose -f infrastructure/docker-compose.yml restart

# ── Zaustavi sve ───────────────────────────────
docker compose -f infrastructure/docker-compose.yml down

# ── Update koda ────────────────────────────────
git pull && npm run build && docker compose -f infrastructure/docker-compose.yml up -d --build

# ── Backup baze ────────────────────────────────
docker exec ketobay_db pg_dump -U ketobay ketobay > backup_$(date +%Y%m%d).sql

# ── Pristupi bazi ──────────────────────────────
docker exec -it ketobay_db psql -U ketobay ketobay

# ── Pristupi Redis ─────────────────────────────
docker exec -it ketobay_redis redis-cli

# ── Ollama modeli ──────────────────────────────
docker exec ketobay_ollama ollama list
docker exec ketobay_ollama ollama pull mistral:7b

# ── Disk usage ─────────────────────────────────
docker system df
df -h /

# ── RAM i CPU ──────────────────────────────────
htop
docker stats
```

---

## 🐛 Troubleshooting

### API ne radi
```bash
docker logs ketobay_api --tail=50
# Najčešći uzrok: DATABASE_URL nije ispravna u .env
docker exec ketobay_api env | grep DATABASE
```

### Nginx 502 Bad Gateway
```bash
docker logs ketobay_nginx --tail=20
# API ili web servis nije gore
docker compose -f infrastructure/docker-compose.yml ps
```

### Ollama ne odgovara
```bash
docker logs ketobay_ollama --tail=30
# Provjeri je li model pullani
docker exec ketobay_ollama ollama list
```

### SSL ne radi
```bash
# Provjeri DNS
nslookup theketobay.com
# IP mora biti tvoj server

# Provjeri certifikat
ls infrastructure/certbot/conf/live/
openssl x509 -in infrastructure/certbot/conf/live/theketobay.com/fullchain.pem -noout -dates
```

### Baza ne prima veze
```bash
docker logs ketobay_db --tail=20
# Provjeri lozinku
docker exec ketobay_db psql -U ketobay -c "SELECT 1;"
```

---

## 📊 Monitoring (opcionalno)

```bash
# Instaliraj Portainer za vizualni Docker management
docker run -d -p 9443:9443 \
  --name portainer \
  -v /var/run/docker.sock:/var/run/docker.sock \
  -v portainer_data:/data \
  portainer/portainer-ce:latest

# Pristup: https://YOUR_SERVER_IP:9443
```

---

## 🔐 Sigurnost poslije deploymenta

```bash
# 1. Promijeni admin lozinku odmah na /admin

# 2. Firewall (samo SSH, HTTP, HTTPS)
ufw allow 22 && ufw allow 80 && ufw allow 443
ufw --force enable

# 3. SSH hardening
nano /etc/ssh/sshd_config
# Promijeni: PasswordAuthentication no (koristiti SSH keys)
systemctl restart sshd

# 4. Provjeri nema exposed portova
netstat -tulpn | grep LISTEN
# 5432, 6379, 11434 NE smiju biti dostupni izvana!
# Sve mora ići kroz 127.0.0.1 ili Docker networking

# 5. Fail2ban
systemctl status fail2ban
```

---

*Deployment guide za TheKetoBay v1.0 · Travanj 2026.*
