createBundleDir = (cfg, bundleDirPath) => {
  if (bundleDirPath) {
    try {
      fs.mkdirSync(bundleDirPath, {recursive: true});
      cfg = {
        ...cfg,
        rollup: {
          ...cfg.rollup,
          bundleDirPath
        }
      };
    } catch (ignored) {
      console.error(
        `Failed to create ${bundleDirPath}; using temp directory instead`
      );
    }
  }
  return {...cfg};
}
']
  },
  reporters: ['mocha'],
  colors: true,
  browsers: ['ChromeHeadless'],
  client: {
    mocha: {
      // this helps debug
      reporter: 'html'
    }
  },
  mochaReporter: {
    showDiff: true
  },
  customLaunchers: {
    ChromeDebug: {
      base: 'Chrome',
      flags: ['--remote-debugging-port=9333']
    }
  }
};

module.exports = config => {
  let bundleDirPath = path.join(BASE_BUNDLE_DIR_PATH, hostname);
  let cfg = {...baseConfig};

  // TO RUN AGAINST SAUCELABS LOCALLY, execute:
  // `CI=1 SAUCE_USERNAME=<user> SAUCE_ACCESS_KEY=<key> npm run test-browser`
  let sauceConfig;

  // configuration for CI mode
  if (env.CI) {
    console.error('CI mode enabled');
    if (env.GITHUB_RUN_ID) {
      console.error('Github Actions detected');
      const buildId = `github-${env.GITHUB_RUN_ID}_${env.GITHUB_RUN_NUMBER}`;
      bundleDirPath = path.join(BASE_BUNDLE_DIR_PATH, buildId);
      sauceConfig = {
        build: buildId
      };
    } else {
      console.error(`Local environment (${hostname}) detected`);
      // don't need to run sauce from Windows CI b/c travis does it.
      if (env.SAUCE_USERNAME || env.SAUCE_ACCESS_KEY) {
        const id = `${hostname} (${Date.now()})`;
        sauceConfig = {
          build: id,
          tunnelIdentifier: id
        };
        console.error('Configured SauceLabs');
      } else {
        console.error(
          'No SauceLabs credentials present; set SAUCE_USERNAME and SAUCE_ACCESS_KEY env vars'
        );
      }
    }
  }

  cfg = createBundleDir(cfg, bundleDirPath);
  cfg = addSauceTests(cfg, sauceConfig);
  cfg = chooseTestSuite(cfg, env.MOCHA_TEST);

  // include sourcemap
  cfg = {
    ...cfg,
    files: [...cfg.files, {pattern: './mocha.js.map', included: false}]
  };

  if (BROWSER) {
    cfg = {
      ...cfg,
      browsers: [BROWSER]
    };
  }

  config.set(cfg);
};

/**
Creates dir `bundleDirPath` if it does not exist; returns new Karma config
containing `bundleDirPath` for rollup plugin.

If this fails, the rollup plugin will use a temp dir.
@param {object} cfg - Karma config.
@param {string} [bundleDirPath] - Path where the output bundle should live
@returns {object} - New Karma config