#!/bin/bash
# Module 4: Websites & Access

cat << 'EOF'
---

## 4️⃣ WEBSITES & ACCESS

### Public Services Status

EOF

# Check website status dynamically
check_website() {
    local url=$1
    local response=$(curl -s -o /dev/null -w "%{http_code}|%{time_total}" --max-time 10 -L "$url" 2>/dev/null)
    local http_code=$(echo "$response" | cut -d'|' -f1)
    local response_time=$(echo "$response" | cut -d'|' -f2)

    # Success codes (2xx, 3xx redirects)
    if [[ "$http_code" =~ ^(200|301|302|303|307|308)$ ]]; then
        echo "✅ OK (${response_time}s)"
    # Authentication required (expected for protected services)
    elif [[ "$http_code" =~ ^(401|403)$ ]]; then
        echo "🔐 Protected"
    # Connection/network errors
    elif [[ "$http_code" == "000" ]]; then
        echo "⚠️ No Response"
    # Other errors
    else
        echo "❌ HTTP $http_code"
    fi
}

# Main services table
echo "| Service | URL | Status | Purpose | Auth |"
echo "|---------|-----|--------|---------|------|"

# Core Business Services
echo "| **Odoo** | https://odoo.ai-impress.com | $(check_website https://odoo.ai-impress.com) | ERP & Business Management | Direct Login |"
echo "| **N8N** | https://n8n.ai-impress.com | $(check_website https://n8n.ai-impress.com) | Workflow Automation | Authentik SSO |"

# Documentation & Wiki
echo "| **Wiki (Outline)** | https://wiki.ai-impress.com | $(check_website https://wiki.ai-impress.com) | Main Knowledge Base | Authentik SSO |"
echo "| **Info (WikiJS)** | https://info.ai-impress.com | $(check_website https://info.ai-impress.com) | Additional Docs | Authentik SSO |"

# Document Management
echo "| **Documenso** | https://sign.ai-impress.com | $(check_website https://sign.ai-impress.com) | E-Signature Platform | Direct Login |"

# Social Media & Communication
echo "| **Postiz** | https://social.ai-impress.com | $(check_website https://social.ai-impress.com) | Social Media Manager | Direct Login |"
echo "| **Postiz Uploads** | https://uploads.ai-impress.com | $(check_website https://uploads.ai-impress.com) | Media Storage | Auto |"
echo "| **Evolution API** | https://wpp.ai-impress.com | $(check_website https://wpp.ai-impress.com) | WhatsApp API | API Key |"

# Backend Services
echo "| **Supabase** | https://supabase.ai-impress.com | $(check_website https://supabase.ai-impress.com) | Backend as a Service | Direct Login |"
echo "| **RabbitMQ** | https://rabbitmq.ai-impress.com | $(check_website https://rabbitmq.ai-impress.com) | Message Queue | Guest Login |"

# Authentication & Security
echo "| **Authentik** | https://auth.ai-impress.com | $(check_website https://auth.ai-impress.com) | Single Sign-On (SSO) | Direct Login |"
echo "| **Vault Admin** | https://vault-admin.ai-impress.com | $(check_website https://vault-admin.ai-impress.com) | Secrets Management UI | Root Token |"
echo "| **Vaultwarden** | https://vault.ai-impress.com | $(check_website https://vault.ai-impress.com) | Password Manager | Direct Login |"

# Monitoring & Admin Tools
echo "| **Grafana** | https://grafana.ai-impress.com | $(check_website https://grafana.ai-impress.com) | Monitoring Dashboard | Admin Only |"
echo "| **Prometheus** | https://prometheus.ai-impress.com | $(check_website https://prometheus.ai-impress.com) | Metrics Database | Admin Only |"
echo "| **Uptime Kuma** | https://status.ai-impress.com | $(check_website https://status.ai-impress.com) | Uptime Monitoring | Direct Login |"
echo "| **Portainer** | https://portainer.ai-impress.com | $(check_website https://portainer.ai-impress.com) | Docker Management UI | Admin Only |"
echo "| **Traefik** | https://traefik.ai-impress.com | $(check_website https://traefik.ai-impress.com) | Reverse Proxy Dashboard | Admin Only |"
echo "| **pgAdmin** | https://pgadmin.ai-impress.com | $(check_website https://pgadmin.ai-impress.com) | PostgreSQL Admin | Direct Login |"

cat << 'EOF'

### Service Categories

**📊 Business Operations:**
- Odoo - Complete ERP system
- N8N - Workflow automation and integrations

**📚 Documentation:**
- Outline (wiki.ai-impress.com) - Primary knowledge base
- WikiJS (info.ai-impress.com) - Additional documentation

**📱 Communication:**
- Postiz - Social media management
- Evolution API - WhatsApp business integration

**🔐 Security & Authentication:**
- Authentik - Central SSO provider
- Vault Admin - Secrets management
- Vaultwarden - Password manager (Bitwarden)

**📈 Monitoring & DevOps:**
- Grafana - Visual dashboards
- Prometheus - Metrics collection
- Uptime Kuma - Service monitoring
- Portainer - Docker management
- Traefik - Reverse proxy & routing

### How to Get Passwords from Vault

```bash
# SSH to server
ssh ubuntu@51.89.231.46

# Set Vault variables
export VAULT_ADDR="http://127.0.0.1:8200"
export VAULT_TOKEN=$(cat /opt/00-infrastructure/vault/.vault-token)

# List all available secrets
vault kv list aimpress/

# Examples: Get specific passwords
vault kv get aimpress/odoo
vault kv get aimpress/authentik
vault kv get aimpress/grafana
vault kv get aimpress/postgres/admin
vault kv get aimpress/n8n
vault kv get aimpress/postiz
vault kv get aimpress/evolution-api
vault kv get aimpress/vaultwarden

# Get in JSON format
vault kv get -format=json aimpress/odoo | jq '.data.data'

# Get single field
vault kv get -field=password aimpress/odoo
```

### Quick Website Health Check

```bash
# Check all websites at once
for site in wiki n8n odoo auth grafana status portainer social sign wpp supabase; do
    echo -n "$site.ai-impress.com: "
    curl -s -o /dev/null -w "%{http_code}" --max-time 5 "https://$site.ai-impress.com"
    echo ""
done

# Check specific site in detail
curl -I https://wiki.ai-impress.com
```

### Service Ports (Internal)

EOF

docker ps --format '{{.Names}}\t{{.Ports}}' | grep -v '^\s*$' | while read -r name ports; do
    if [[ -n "$ports" ]]; then
        echo "- **$name**: $ports"
    fi
done

cat << 'EOF'

### Common Admin Tasks

```bash
# Restart a service
cd /opt/<service-name>
docker-compose restart

# View service logs
docker logs -f --tail 100 <container-name>

# Check SSL certificates
echo | openssl s_client -servername wiki.ai-impress.com -connect wiki.ai-impress.com:443 2>/dev/null | openssl x509 -noout -dates

# Renew all Let's Encrypt certificates (automatic via Traefik)
docker restart traefik

# Check Traefik routing
docker logs traefik --tail 100 | grep -i error
```

### Adding New Service

To add a new service to the system:

1. **Create docker-compose.yml** in `/opt/<service-name>/`
2. **Add Traefik labels** for routing:
   ```yaml
   labels:
     - "traefik.enable=true"
     - "traefik.http.routers.<name>.rule=Host(`subdomain.ai-impress.com`)"
     - "traefik.http.routers.<name>.entrypoints=websecure"
     - "traefik.http.routers.<name>.tls.certresolver=letsencrypt"
   ```
3. **Add to monitoring** in health-check-alerting.sh
4. **Save credentials** to Vault:
   ```bash
   vault kv put aimpress/<service> \
     username="admin" \
     password="<generated-password>" \
     url="https://subdomain.ai-impress.com"
   ```
5. **Start service**: `docker-compose up -d`
EOF
