class ChangePrimaryGatewayService {

    public String selectNewPrimaryGatewayInstanceId(Stack stack, List<String> repairInstanceIds) {
        String newPrimaryGatewayInstanceId;
        try {
            GatewayConfig currentPrimaryGatewayConfig = gatewayConfigService.getPrimaryGatewayConfig(stack);
            Optional<String> freeIpaMasterInstanceId = findFreeIpaMasterInstanceId(stack, currentPrimaryGatewayConfig);
            if (freeIpaMasterInstanceId.isPresent() && !repairInstanceIds.contains(freeIpaMasterInstanceId.get())) {
                LOGGER.debug("Using the FreeIPA master as the new primary gateway");
                newPrimaryGatewayInstanceId = freeIpaMasterInstanceId.get();
            } else {
                newPrimaryGatewayInstanceId = currentPrimaryGatewayConfig.getInstanceId();
                if (repairInstanceIds.contains(newPrimaryGatewayInstanceId)) {
                    LOGGER.debug("The current primary gateway is on the list of to avoid, searching for a different primary gateway");
                    newPrimaryGatewayInstanceId = assignNewPrimaryGatewayInstanceId(stack, repairInstanceIds);
                }
            }
        } catch (NotFoundException e) {
            LOGGER.debug("No primary gateway found, searching for an different primary gateway");
            newPrimaryGatewayInstanceId = assignNewPrimaryGatewayInstanceId(stack, repairInstanceIds);
        } catch (CloudbreakOrchestratorException e) {
            LOGGER.debug("The orchestrator failed to identify the primary gateway node", e);
            throw new NotFoundException("No FreeIPA primary gateway could be selected", e);
        }
        LOGGER.debug("The new primary gateway will be {}", newPrimaryGatewayInstanceId);
        return newPrimaryGatewayInstanceId;
    }

}