#!/bin/bash
# 🚀 Auto-generated by The AltStack
# https://thealtstack.com

echo "🔵 Starting AltStack Deployment..."

# 1. Check/Install Docker
if ! command -v docker &> /dev/null; then
    echo "📦 Docker not found. Installing..."
    curl -fsSL https://get.docker.com -o get-docker.sh
    sh get-docker.sh
    rm get-docker.sh
    echo "✅ Docker installed."
else
    echo "✅ Docker is already installed."
fi

# 2. Setup Directory
APP_DIR="posthog-deploy"
mkdir -p $APP_DIR
cd $APP_DIR
echo "📂 Created directory: $APP_DIR"

# 3. Create docker-compose.yml
echo "📄 Writing configuration..."
cat << 'INNER_EOF' > docker-compose.yml

# -------------------------------------------------------------------------
# 🚀 Created and distributed by The AltStack
# 🌍 https://thealtstack.com
# -------------------------------------------------------------------------

version: '3.8'

services:
  db:
    image: postgres:14-alpine
    container_name: posthog-db
    restart: unless-stopped
    environment:
      - POSTGRES_PASSWORD=posthog
      - POSTGRES_DB=posthog
      - POSTGRES_USER=posthog
    volumes:
      - posthog_postgres_data:/var/lib/postgresql/data

  redis:
    image: redis:6-alpine
    container_name: posthog-redis
    restart: unless-stopped
    volumes:
      - posthog_redis_data:/data

  clickhouse:
    image: clickhouse/clickhouse-server:22.3-alpine
    container_name: posthog-clickhouse
    restart: unless-stopped
    environment:
      - CLICKHOUSE_DB=posthog
      - CLICKHOUSE_USER=default
      - CLICKHOUSE_PASSWORD=
    volumes:
      - posthog_clickhouse_data:/var/lib/clickhouse

  kafka:
    image: confluentinc/cp-kafka:7.5.3
    container_name: posthog-kafka
    restart: unless-stopped
    depends_on:
      - zookeeper
    environment:
      - KAFKA_ZOOKEEPER_CONNECT=zookeeper:2181
      - KAFKA_ADVERTISED_LISTENERS=PLAINTEXT://kafka:9092
      - KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR=1

  zookeeper:
    image: confluentinc/cp-zookeeper:7.5.3
    container_name: posthog-zookeeper
    restart: unless-stopped
    environment:
      - ZOOKEEPER_CLIENT_PORT=2181
      - ZOOKEEPER_TICK_TIME=2000

  posthog:
    image: posthog/posthog:release-1.40.0
    container_name: posthog
    restart: unless-stopped
    depends_on:
      - db
      - redis
      - clickhouse
      - kafka
    ports:
      - "8000:8000"
    environment:
      - DATABASE_URL=postgres://posthog:posthog@db:5432/posthog
      - REDIS_URL=redis://redis:6379/
      - CLICKHOUSE_HOST=clickhouse
      - KAFKA_HOSTS=kafka:9092
      - SECRET_KEY=please-change-this-secret-key-in-production-12345
      - SKIP_SERVICE_VERSION_REQUIREMENTS=1
    volumes:
      - ./uploads:/app/static/uploads

volumes:
  posthog_postgres_data:
  posthog_redis_data:
  posthog_clickhouse_data:

INNER_EOF

# 4. Start Services
echo "🚀 Starting services..."
docker compose up -d

echo ""
echo "✅ Deployment Complete!"
echo "👉 Your posthog stack is running."
