#!/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="affine-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
# -------------------------------------------------------------------------

# Docker Compose for AFFiNE
version: '3.8'

services:
  affine:
    image: ghcr.io/toeverything/affine-graphql:latest # Using official as fallback but custom build setup exists in Dockerfile
    container_name: affine
    ports:
      - "3000:3000"
    environment:
      - DATABASE_URL=postgres://affine:affine@db:5432/affine
      - REDIS_URL=redis://redis:6379
      - NODE_ENV=production
    depends_on:
      db:
        condition: service_healthy
      redis:
        condition: service_healthy
    networks:
      - affine_net
    healthcheck:
      test: [ "CMD", "curl", "-f", "http://localhost:3000/" ]
      interval: 30s
      timeout: 10s
      retries: 3

  db:
    image: postgres:15-alpine
    container_name: affine-db
    environment:
      POSTGRES_USER: affine
      POSTGRES_PASSWORD: affine
      POSTGRES_DB: affine
    volumes:
      - affine_db_data:/var/lib/postgresql/data
    networks:
      - affine_net
    healthcheck:
      test: [ "CMD-SHELL", "pg_isready -U affine" ]
      interval: 5s
      timeout: 5s
      retries: 5

  redis:
    image: redis:7-alpine
    container_name: affine-redis
    networks:
      - affine_net
    healthcheck:
      test: [ "CMD", "redis-cli", "ping" ]
      interval: 5s
      timeout: 5s
      retries: 5

networks:
  affine_net:
    driver: bridge

volumes:
  affine_db_data:
    name: affine_db_data

INNER_EOF

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

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