#!/usr/bin/env bash
# deploy-matrix.sh — Deploy Conduit Matrix homeserver for Timmy fleet
# Usage: ./deploy-matrix.sh [DOMAIN]
#
# Issue: #166 / #183

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DOMAIN="${1:-${MATRIX_DOMAIN:-}}"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

log() { echo -e "${GREEN}[deploy-matrix]${NC} $*"; }
warn() { echo -e "${YELLOW}[deploy-matrix]${NC} $*"; }
error() { echo -e "${RED}[deploy-matrix]${NC} $*" >&2; }

# === Pre-flight checks ===
log "Starting Matrix/Conduit deployment..."

if [[ -z "$DOMAIN" ]]; then
    error "DOMAIN not specified. Usage: ./deploy-matrix.sh matrix.timmy.foundation"
    error "Or set MATRIX_DOMAIN environment variable."
    exit 1
fi

if [[ ! -f "$SCRIPT_DIR/.env" ]]; then
    error ".env file not found. Copy .env.example to .env and configure."
    exit 1
fi

if [[ ! -f "$SCRIPT_DIR/conduit.toml" ]]; then
    error "conduit.toml not found. Copy from scaffold and configure."
    exit 1
fi

# Check for placeholder values
if grep -q "YOUR_DOMAIN_HERE" "$SCRIPT_DIR/conduit.toml"; then
    error "conduit.toml still contains YOUR_DOMAIN_HERE placeholder."
    error "Please edit and replace with actual domain: $DOMAIN"
    exit 1
fi

if grep -q "CHANGE_ME" "$SCRIPT_DIR/.env"; then
    warn ".env contains CHANGE_ME placeholders. Ensure secrets are set."
fi

# Check Docker availability
if ! command -v docker &>/dev/null; then
    error "Docker not found. Install: curl -fsSL https://get.docker.com | sh"
    exit 1
fi

if ! docker compose version &>/dev/null; then
    error "Docker Compose not found."
    exit 1
fi

log "Pre-flight checks passed. Domain: $DOMAIN"

# === Directory setup ===
log "Creating data directories..."
mkdir -p "$SCRIPT_DIR/data/conduit"
mkdir -p "$SCRIPT_DIR/data/caddy"

# === Load environment ===
set -a
source "$SCRIPT_DIR/.env"
set +a

# === Pull and start ===
log "Pulling Conduit image..."
docker compose -f "$SCRIPT_DIR/docker-compose.yml" pull

log "Starting Conduit..."
docker compose -f "$SCRIPT_DIR/docker-compose.yml" up -d

# === Wait for health ===
log "Waiting for Conduit healthcheck..."
for i in {1..30}; do
    if docker compose -f "$SCRIPT_DIR/docker-compose.yml" ps conduit | grep -q "healthy"; then
        log "Conduit is healthy!"
        break
    fi
    if [[ $i -eq 30 ]]; then
        error "Conduit failed to become healthy within 5 minutes."
        docker compose -f "$SCRIPT_DIR/docker-compose.yml" logs --tail 50 conduit
        exit 1
    fi
    sleep 10
done

# === Post-deploy info ===
log "Deployment complete!"
echo ""
echo "=========================================="
echo "Matrix homeserver deployed at: $DOMAIN"
echo "=========================================="
echo ""
echo "Next steps:"
echo "  1. Ensure reverse proxy (Caddy/Nginx) forwards to localhost:6167"
echo "  2. Create admin account with:"
echo "     curl -X POST https://$DOMAIN/_matrix/client/v3/register"
echo "       -H Content-Type: application/json"
echo "       -d {"username":"admin","password":"YOUR_PASS","auth":{"type":"m.login.dummy"}}"
echo "  3. Create fleet rooms via Element or API"
echo "  4. Configure Hermes gateway for Matrix platform"
echo ""
echo "Logs: docker compose -f $SCRIPT_DIR/docker-compose.yml logs -f"
echo "Stop: docker compose -f $SCRIPT_DIR/docker-compose.yml down"