services:
  affine:
    image: ghcr.io/toeverything/affine:${AFFINE_REVISION:-stable}
    container_name: affine_server
    depends_on:
      redis:
        condition: service_healthy
      affine_migration:
        condition: service_completed_successfully

    volumes:
      - ${UPLOAD_LOCATION}:/root/.affine/storage
      - ${CONFIG_LOCATION}:/root/.affine/config

    env_file:
      - .env

    environment:
      - REDIS_SERVER_HOST=redis
      - DATABASE_URL=postgresql://${DB_USERNAME}:${DB_PASSWORD}@postgresql:5432/${DB_DATABASE:-affine}
      - AFFINE_INDEXER_ENABLED=false

    labels:
      - "traefik.enable=true"
      - "traefik.docker.network=traefik-network"
      - "traefik.http.routers.affine.rule=Host(`affine.byhaider.dev`)"
      - "traefik.http.routers.affine.entrypoints=websecure"
      - "traefik.http.routers.affine.tls=true"
      - "traefik.http.routers.affine.tls.certresolver=cloudflare"
      - "traefik.http.services.affine.loadbalancer.server.port=3010"

    networks:
      - traefik-network
      - postgresql

    restart: unless-stopped


  affine_migration:
    image: ghcr.io/toeverything/affine:${AFFINE_REVISION:-stable}
    container_name: affine_migration_job

    volumes:
      - ${UPLOAD_LOCATION}:/root/.affine/storage
      - ${CONFIG_LOCATION}:/root/.affine/config

    command: ['sh', '-c', 'node ./scripts/self-host-predeploy.js']

    env_file:
      - .env

    environment:
      - REDIS_SERVER_HOST=redis
      - DATABASE_URL=postgresql://${DB_USERNAME}:${DB_PASSWORD}@postgresql:5432/${DB_DATABASE:-affine}
      - AFFINE_INDEXER_ENABLED=false

    depends_on:
      redis:
        condition: service_healthy

    networks:
      - postgresql

  redis:
    image: redis
    container_name: affine_redis

    healthcheck:
      test: ['CMD', 'redis-cli', '--raw', 'incr', 'ping']
      interval: 10s
      timeout: 5s
      retries: 5

    networks:
      - postgresql

    restart: unless-stopped


networks:
  traefik-network:
    external: true
  postgresql:
    external: true