services:
  cert-gen:
    image: alpine
    volumes:
      - ./certs:/certs
    command: >
      sh -c "
      if [ ! -f /certs/ca.pem ]; then
        echo 'SSL certificates not found. Generating certificates...' &&
        apk add --no-cache openssl &&
        openssl genrsa -out /certs/ca-key.pem 2048 &&
        openssl req -new -x509 -nodes -days 365 -key /certs/ca-key.pem -out /certs/ca.pem -subj '/C=US/ST=CA/L=San Francisco/O=Mojaloop/OU=Database/CN=MySQL_CA' &&
        openssl genrsa -out /certs/server-key.pem 2048 &&
        openssl req -new -key /certs/server-key.pem -out /certs/server.csr -subj '/C=US/ST=CA/L=San Francisco/O=Mojaloop/OU=Database/CN=mysql' &&
        echo '[v3_req]' > /tmp/cert.conf &&
        echo 'basicConstraints = CA:FALSE' >> /tmp/cert.conf &&
        echo 'keyUsage = nonRepudiation, digitalSignature, keyEncipherment' >> /tmp/cert.conf &&
        echo 'subjectAltName = @alt_names' >> /tmp/cert.conf &&
        echo '[alt_names]' >> /tmp/cert.conf &&
        echo 'DNS.1 = mysql' >> /tmp/cert.conf &&
        echo 'DNS.2 = localhost' >> /tmp/cert.conf &&
        echo 'IP.1 = 127.0.0.1' >> /tmp/cert.conf &&
        openssl x509 -req -days 365 -in /certs/server.csr -CA /certs/ca.pem -CAkey /certs/ca-key.pem -CAcreateserial -out /certs/server-cert.pem -extensions v3_req -extfile /tmp/cert.conf &&
        rm -f /certs/*.csr /certs/*.srl /tmp/cert.conf &&
        chmod 644 /certs/ca.pem /certs/server-cert.pem &&
        chmod 644 /certs/ca-key.pem /certs/server-key.pem &&
        echo 'SSL certificates generated successfully!' &&
        echo 'Generated certificate files with permissions:' &&
        ls -la /certs/ &&
        echo 'Certificate files should be readable by any user for CI compatibility.'
      else
        echo 'SSL certificates found. Ready to start MySQL.'
      fi
      "
    restart: "no"

  mysql:
    image: mysql:8.0
    depends_on:
      cert-gen:
        condition: service_completed_successfully
    environment:
      MYSQL_ROOT_PASSWORD: example_root_password
      MYSQL_DATABASE: example_db
      MYSQL_USER: example_user
      MYSQL_PASSWORD: example_password
    command:
      - --ssl-ca=/etc/mysql/certs/ca.pem
      - --ssl-cert=/etc/mysql/certs/server-cert.pem
      - --ssl-key=/etc/mysql/certs/server-key.pem
      - --bind-address=0.0.0.0
      - --require_secure_transport=ON
    ports:
      - "3306:3306"
    volumes:
      - mysql_data:/var/lib/mysql
      - ./certs:/etc/mysql/certs:ro
    healthcheck:
      test: ["CMD", "mysqladmin", "ping", "-h", "localhost"]
      timeout: 5s
      retries: 10
      start_period: 30s

volumes:
  mysql_data:
