# BMC Hub - Production Deployment Guide

## 📋 Forudsætninger

- Linux server med **Podman** eller **Docker** installeret
- Adgang til Gitea repository: `https://g.bmcnetworks.dk/ct/bmc_hub`
- Gitea Personal Access Token med læseadgang

## 🚀 Deployment Trin-for-Trin

### 1. Opret Gitea Personal Access Token

1. Gå til https://g.bmcnetworks.dk/user/settings/applications
2. Klik "Generate New Token"
3. Giv tokenet et navn: "BMC Hub Production"
4. Vælg scopes: `repo` (read)
5. Gem tokenet sikkert - det vises kun én gang

### 2. Tag en Release i Gitea

Fra din lokale udviklings-mac:

```bash
cd /Users/christianthomas/DEV/bmc_hub_dev

# Commit alle ændringer
git add .
git commit -m "Prepare for production v1.0.0"

# Tag release
git tag v1.0.0
git push origin main
git push origin v1.0.0
```

### 3. Forbered Production Server

```bash
# SSH til production server
ssh user@your-production-server.com

# Opret deployment directory
mkdir -p /srv/podman/bmc_hub_v1.0
cd /srv/podman/bmc_hub_v1.0

# Download kun nødvendige filer fra Gitea
curl -H "Authorization: token YOUR_GITEA_TOKEN" \
     https://g.bmcnetworks.dk/api/v1/repos/ct/bmc_hub/raw/docker-compose.prod.yml?ref=v1.0.0 \
     -o docker-compose.yml

mkdir -p /srv/podman/bmc_hub_v1.0 && cd /srv/podman/bmc_hub_v1.0 && curl -H "Authorization: token 58419ee1f9503a95b58e56448db6f77a6caddff6" https://g.bmcnetworks.dk/api/v1/repos/ct/bmc_hub/raw/scripts/deploy_production.sh?ref=v1.0.1 -o setup.sh && chmod +x setup.sh

curl -H "Authorization: token YOUR_GITEA_TOKEN" \
     https://g.bmcnetworks.dk/api/v1/repos/ct/bmc_hub/raw/.env.prod.example?ref=v1.0.0 \
     -o .env.example

# Opret migrations directory
mkdir -p migrations

# Download alle migrations (init.sql og andre)
curl -H "Authorization: token YOUR_GITEA_TOKEN" \
     https://g.bmcnetworks.dk/api/v1/repos/ct/bmc_hub/raw/migrations/init.sql?ref=v1.0.0 \
     -o migrations/init.sql

# Download requirements.txt (til Dockerfile)
curl -H "Authorization: token YOUR_GITEA_TOKEN" \
     https://g.bmcnetworks.dk/api/v1/repos/ct/bmc_hub/raw/requirements.txt?ref=v1.0.0 \
     -o requirements.txt
```

### 4. Konfigurer Environment Variables

```bash
# Kopier template
cp .env.example .env

# Rediger .env med production værdier
nano .env
```

**VIGTIGE ÆNDRINGER I .env:**

```bash
# Release version (matcher git tag)
RELEASE_VERSION=v1.0.3

# Gitea server URL
GITEA_URL=https://g.bmcnetworks.dk

# Gitea token
GITHUB_TOKEN=din_gitea_personal_access_token

# SKIFT ALLE PASSWORDS!
POSTGRES_PASSWORD=et_meget_stærkt_password_her
SECRET_KEY=$(python3 -c "import secrets; print(secrets.token_urlsafe(32))")

# Production settings
LOG_LEVEL=WARNING
CORS_ORIGINS=http://172.16.31.183:8001

# BEHOLD SAFETY SWITCHES PÅ!
# VIGTIGT: Brug IKKE inline kommentarer på boolean værdier (kun 'true' eller 'false')
ECONOMIC_READ_ONLY=true
ECONOMIC_DRY_RUN=true
```

### 5. Opret Nødvendige Directories

```bash
cd /srv/podman/bmc_hub_v1.0

# Opret data directories
mkdir -p logs uploads data/invoice_templates

# Sæt permissions (hvis nødvendigt)
chmod 755 logs uploads data
```

### 6. Start Services med Podman Compose

```bash
# Pull og build images
podman-compose -f docker-compose.yml build --no-cache

# Start services
podman-compose -f docker-compose.yml up -d

# Følg logs
podman-compose -f docker-compose.yml logs -f
```

### 7. Verificer Deployment

```bash
# Check container status
podman ps

# Test health endpoint
curl http://localhost:8000/health

# Check database
podman exec -it bmc-hub-postgres-prod psql -U bmc_hub_prod -d bmc_hub_prod -c "\dt"
```

Expected output:
```json
{
  "status": "healthy",
  "database": "connected",
  "version": "v1.0.0"
}
```

## 🔄 Opdatering til Ny Version

```bash
# På din Mac - tag ny release
cd /Users/christianthomas/DEV/bmc_hub_dev
git tag v1.1.0
git push origin v1.1.0

# På production server
cd /srv/podman/bmc_hub_v1.0

# Opdater RELEASE_VERSION i .env
nano .env  # Ændr til v1.1.0

# Rebuild og genstart
podman-compose down
podman-compose build --no-cache
podman-compose up -d

# Verificer
podman-compose logs -f api
```

## 🗄️ Database Migrations

Når der tilføjes nye migrations:

```bash
# Download nye migration filer til /srv/podman/bmc_hub_v1.0/migrations/
curl -H "Authorization: token YOUR_TOKEN" \
     https://g.bmcnetworks.dk/api/v1/repos/ct/bmc_hub/raw/migrations/XXX_new_migration.sql?ref=v1.1.0 \
     -o migrations/XXX_new_migration.sql

# Kør migration manuelt
podman exec -i bmc-hub-postgres-prod psql -U bmc_hub_prod -d bmc_hub_prod < migrations/XXX_new_migration.sql
```

**VIGTIGT:** init.sql kører KUN ved første database initialization. Nye migrations skal køres manuelt.

## 🔒 Sikkerhed Best Practices

1. **Passwords**: Brug minimum 32 tegn, tilfældige passwords
2. **Secret Key**: Generer med `secrets.token_urlsafe(32)`
3. **Gitea Token**: Begræns til read-only scope for production
4. **Firewall**: Åbn kun nødvendige porte (8000, 5432 hvis remote access)
5. **HTTPS**: Brug reverse proxy (nginx/traefik) med SSL i production
6. **Backups**: Sæt automatisk backup op for PostgreSQL data volume

## 📊 Monitoring

```bash
# Container status
podman-compose ps

# Resource usage
podman stats

# Application logs
podman-compose logs -f api

# Database logs
podman-compose logs -f postgres

# Health check
curl http://localhost:8000/health
curl http://localhost:8000/api/v1/system/health
```

## 🆘 Troubleshooting

### Database Connection Issues

```bash
# Check postgres logs
podman-compose logs postgres

# Test connection
podman exec -it bmc-hub-postgres-prod psql -U bmc_hub_prod -d bmc_hub_prod

# Check network
podman network inspect bmc-hub-network_bmc-hub-network
```

### API Won't Start

```bash
# Check detailed logs
podman logs bmc-hub-api-prod

# Verify environment variables
podman exec bmc-hub-api-prod env | grep -E "DATABASE|RELEASE"

# Check if database is ready
podman exec bmc-hub-postgres-prod pg_isready
```

### Gitea Download Fails

```bash
# Test token manually
curl -H "Authorization: token YOUR_TOKEN" \
     https://g.bmcnetworks.dk/api/v1/repos/ct/bmc_hub/tags

# Verify release exists
curl https://g.bmcnetworks.dk/ct/bmc_hub/releases
```

## 🔄 Rollback Procedure

```bash
# Ændr RELEASE_VERSION til tidligere version
nano .env  # v1.1.0 → v1.0.0

# Rebuild med gammel version
podman-compose down
podman-compose build --no-cache
podman-compose up -d
```

## 📦 Backup & Restore

### Backup Database

```bash
# Automated backup script
podman exec bmc-hub-postgres-prod pg_dump -U bmc_hub_prod bmc_hub_prod > backup_$(date +%Y%m%d).sql

# Eller med podman-compose
podman-compose exec postgres pg_dump -U bmc_hub_prod bmc_hub_prod > backup.sql
```

### Restore Database

```bash
# Stop API først
podman-compose stop api

# Restore
podman exec -i bmc-hub-postgres-prod psql -U bmc_hub_prod -d bmc_hub_prod < backup.sql

# Start API
podman-compose start api
```

## 🎯 Production Checklist

- [ ] Gitea token oprettet med read-only scope
- [ ] Release tagged i Git (f.eks. v1.0.0)
- [ ] `.env` fil udfyldt med production værdier
- [ ] Alle passwords ændret fra defaults
- [ ] SECRET_KEY genereret tilfældigt
- [ ] CORS_ORIGINS sat til production domain
- [ ] Safety switches aktiveret (READ_ONLY=true, DRY_RUN=true)
- [ ] Directories oprettet (logs, uploads, data)
- [ ] Migrations downloaded til `migrations/` directory
- [ ] Database initialiseret med init.sql
- [ ] Containers startet og healthy
- [ ] Health endpoints verificeret
- [ ] Backup strategi implementeret
- [ ] Firewall konfigureret
- [ ] SSL certifikat installeret (reverse proxy)
- [ ] Monitoring setup (optional: Uptime Kuma)

## 📞 Support

Ved problemer, kontakt: ct@bmcnetworks.dk
