services:
  postgres:
    image: postgres:18-alpine
    container_name: postgres-postgres
    restart: unless-stopped
    environment:
      POSTGRES_DB: ${POSTGRES_DB:-postgres}
      POSTGRES_USER: ${POSTGRES_USER:-postgres}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
      POSTGRES_INITDB_ARGS: "--encoding=UTF8 --locale=C"
      PROJECT_NAME: ${PROJECT_NAME:-Generic PostgreSQL}
      PROJECT_SCHEMA: ${PROJECT_SCHEMA:-none}
    ports:
      - "5432:5432"
    volumes:
      - postgres_data:/var/lib/postgresql/data
      - ${JENKINS_WORKSPACE:-./postgresql}/init:/docker-entrypoint-initdb.d
      - ${JENKINS_WORKSPACE:-./postgresql}/conf:/etc/postgresql:ro
    command: >
      postgres
      -c config_file=/etc/postgresql/postgresql.conf
      -c hba_file=/etc/postgresql/pg_hba.conf
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-postgres} -d ${POSTGRES_DB:-postgres}"]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 30s
    deploy:
      resources:
        limits:
          memory: 3G
          cpus: '3.0'
        reservations:
          memory: 1.5G
          cpus: '1.0'
    security_opt:
      - no-new-privileges:true
    logging:
      driver: "json-file"
      options:
        max-size: "10m"
        max-file: "3"
    networks:
      - datashield-network

  postgres-backup:
    image: postgres:18-alpine
    container_name: datashield-backup
    restart: unless-stopped
    environment:
      PGPASSWORD: ${POSTGRES_PASSWORD}
      BACKUP_SCHEDULE: ${BACKUP_SCHEDULE:-0 2 * * *}
      BACKUP_RETENTION: ${BACKUP_RETENTION:-7}
      POSTGRES_DB: ${POSTGRES_DB:-datashield}
      POSTGRES_USER: ${POSTGRES_USER:-collabhubmaster}
    volumes:
      - ${JENKINS_WORKSPACE:-./postgresql}/../backups:/backups
      - ${JENKINS_WORKSPACE:-./postgresql}/scripts:/scripts
      - postgres_data:/var/lib/postgresql/data:ro
    command: >
      sh -c "
      echo 'Setting up backup scheduler...' &&
      echo '${BACKUP_SCHEDULE:-0 2 * * *} /scripts/backup.sh' > /tmp/crontab &&
      crontab /tmp/crontab &&
      echo 'Starting cron daemon...' &&
      crond -f -l 2
      "
    depends_on:
      postgres:
        condition: service_healthy
    networks:
      - datashield-network

  adminer:
    image: adminer:latest
    container_name: datashield-admin
    restart: unless-stopped
    ports:
      - "8080:8080"
    environment:
      ADMINER_DEFAULT_SERVER: postgres
    depends_on:
      postgres:
        condition: service_healthy
    networks:
      - datashield-network
    profiles:
      - development  # Only start with --profile development

volumes:
  postgres_data:
    driver: local

networks:
  datashield-network:
    driver: bridge
    ipam:
      config:
        - subnet: 172.21.0.0/16