#!/bin/bash
set -e

REPORT_DIR="/opt/infrastructure-docs/reports"
mkdir -p "$REPORT_DIR"
REPORT_FILE="$REPORT_DIR/infrastructure-complete-$(date +%Y%m%d-%H%M%S).md"

# Colors
CYAN='\033[0;36m'
GREEN='\033[0;32m'
NC='\033[0m'

echo -e "${CYAN}[$(date +%H:%M:%S)]${NC} Starting Infrastructure Report..."

# Collect data
REPORT_TIME=$(date +'%Y-%m-%d %H:%M:%S')
DOCKER_RUNNING=$(docker ps -q 2>/dev/null | wc -l)
DOCKER_TOTAL=$(docker ps -aq 2>/dev/null | wc -l)

# Start writing report
exec 3> "$REPORT_FILE"

cat >&3 << EOF
# 🏗️ Complete Infrastructure Report for AI-Impress

> **Generated:** $REPORT_TIME
> **Host:** $(hostname) | **IP:** 51.89.231.46
> **Status:** $DOCKER_RUNNING containers running / $DOCKER_TOTAL total

---

## 📑 TABLE OF CONTENTS

1. [Executive Summary](#executive-summary) - Quick overview
2. [Service Inventory](#service-inventory) - What we have
3. [How to Manage](#how-to-manage) - Do it yourself
4. [Current Status](#current-status) - What's working
5. [Troubleshooting](#troubleshooting) - Fix problems

---

## 1️⃣ EXECUTIVE SUMMARY

### Quick Health Check
- 🐳 **Containers:** $DOCKER_RUNNING running / $DOCKER_TOTAL total
- 💾 **Backups:** $(du -sh /mnt/backups 2>/dev/null | cut -f1 || echo "N/A")
- 💿 **Databases:** $(du -sh /mnt/psql-data 2>/dev/null | cut -f1 || echo "N/A")
- 🌐 **Networks:** $(docker network ls -q 2>/dev/null | wc -l)
- 📦 **Volumes:** $(docker volume ls -q 2>/dev/null | wc -l)

### What This System Does
- **Wiki & Documentation** (Outline)
- **Workflow Automation** (N8N)
- **CRM & Marketing** (Mautic)
- **Business Management** (Odoo)
- **Team Auth** (Authentik)
- **Backups & Recovery** (Restic)

---

## 2️⃣ SERVICE INVENTORY

### 🏛️ CRITICAL - CANNOT DELETE
Must stay running or everything breaks:

| Service | Container | Purpose | Port |
|---------|-----------|---------|------|
| **Traefik** | traefik | Reverse proxy, SSL | 80, 443 |
| **PostgreSQL** | postgres-main | Main database | 5432 |
| **Redis** | redis-main | Cache & queues | 6379 |
| **Vault** | vault | Secrets | 8200 |

### 💼 BUSINESS APPLICATIONS

| Service | URL | Delete? |
|---------|-----|---------|
| **Outline** | https://wiki.ai-impress.com | ⚠️ Data loss |
| **N8N** | https://n8n.ai-impress.com | ⚠️ Data loss |
| **Mautic** | https://marketing.ai-impress.com | ⚠️ Data loss |
| **Odoo** | https://odoo.ai-impress.com | ⚠️ Data loss |
| **Authentik** | https://auth.ai-impress.com | ❌ Breaks login |
| **Portainer** | https://portainer.ai-impress.com | ✅ Safe |
| **Grafana** | https://grafana.ai-impress.com | ✅ Safe |

---

## 3️⃣ HOW TO MANAGE

### ✏️ Change PostgreSQL Password

\`\`\`bash
# 1. SSH to server
ssh ubuntu@51.89.231.46

# 2. Generate new password
NEW_PASS=\$(openssl rand -base64 32)

# 3. Change in database
docker exec postgres-main psql -U aimpress_admin -c "ALTER USER outline_user WITH PASSWORD '\$NEW_PASS';"

# 4. Save password
vault kv put aimpress/postgres/outline password=\$NEW_PASS

# 5. Restart service
cd /opt/02-core/outline && docker-compose restart

# 6. Test
curl -s https://wiki.ai-impress.com
\`\`\`

### 🗑️ Delete Container

\`\`\`bash
# Backup first!
docker exec <container> mysqldump --all-databases > /tmp/backup.sql

# Stop and remove
docker-compose -f /opt/path stop <container>
docker rm <container>

# Update docker-compose.yml
nano /opt/path/docker-compose.yml

# Restart
docker-compose up -d
\`\`\`

### 🔄 Restart Service

\`\`\`bash
docker restart <container>
docker-compose -f /opt/path restart
\`\`\`

### 📊 View Logs

\`\`\`bash
docker logs -f --tail 50 <container>
\`\`\`

---

## 4️⃣ CURRENT STATUS

### Containers
EOF

docker ps --format "table {{.Names}}\t{{.Status}}" | awk 'NR>1 {printf "- %s: %s\n", $1, substr($0, index($0,$2))}' >&3

cat >&3 << EOF

### Websites
EOF

for domain in wiki.ai-impress.com n8n.ai-impress.com marketing.ai-impress.com odoo.ai-impress.com; do
  if timeout 3 curl -skI "https://$domain" 2>/dev/null | grep -q "HTTP"; then
    echo "- ✅ $domain" >&3
  else
    echo "- ❌ $domain" >&3
  fi
done

cat >&3 << EOF

---

## 5️⃣ TROUBLESHOOTING

### Website not responding
\`\`\`bash
docker ps | grep traefik  # Check Traefik
docker logs traefik       # View logs
\`\`\`

### Database error
\`\`\`bash
docker ps | grep postgres  # Check PostgreSQL
docker logs postgres-main  # View logs
df -h /mnt/psql-data      # Check disk
\`\`\`

### Out of disk space
\`\`\`bash
du -sh /opt/* /mnt/* | sort -h
find /opt/05-backups/logs -mtime +30 -delete
ls -t /mnt/backups/postgresql-*.sql.gz | tail -n +11 | xargs rm
\`\`\`

---

**Generated:** $(date)
**Location:** /opt/infrastructure-docs/reports/

EOF

exec 3>&-

echo -e "${GREEN}✅ Report generated: $REPORT_FILE${NC}"
