/**
*
*/
(function() {
'use strict';
load("jstests/libs/fail_point_util.js");
load('jstests/replsets/rslib.js');
const basename = 'initial_sync_rename_database_before_cloning';
jsTestLog('Bring up a replica set');
const rst = new ReplSetTest({name: basename, nodes: 1});
rst.startSet();
rst.initiate();
const dbName = "test";
const primary = rst.getPrimary();
const primaryDb = primary.getDB(dbName);
jsTestLog("Create collections on primary");
const collName = "coll";
jsTestLog('Waiting for replication');
rst.awaitReplication();
jsTestLog('Bring up a new node');
const secondary = rst.add({setParameter: 'numInitialSyncAttempts=1'});
const failPoint = configureFailPoint(secondary, 'initialSyncHangBeforeCopyingDatabases');
jsTestLog('Begin initial sync on secondary');
let conf = rst.getPrimary().getDB('admin').runCommand({replSetGetConfig: 1}).config;
conf.members.push({_id: 1, host: secondary.host, priority: 0, votes: 0});
conf.version++;
assert.commandWorked(rst.getPrimary().getDB('admin').runCommand({replSetReconfig: conf}));
assert.eq(primary, rst.getPrimary(), 'Primary changed after reconfig');
jsTestLog('Waiting for initial sync to start');
failPoint.wait();
assert.commandWorked(primaryDb.getCollection(collName).insert({}));
assert.commandWorked(primaryDb.runCommand({emptycapped: "coll"}))
assert.commandWorked(primaryDb.getCollection(collName).insert({_id: 0, a: 1}));
jsTestLog('Build index on the sync source');
const fpIndexSrc = configureFailPoint(primary, 'hangAfterStartingIndexBuild');
const awaitIndex = startParallelShell(() => {
assert.commandWorked(db.getCollection('coll').createIndex({a: 1}));
}, primary.port)
jsTestLog('Pause index build on sync source')
fpIndexSrc.wait();
const fpIndexInit = configureFailPoint(secondary, 'hangAfterStartingIndexBuild');
jsTestLog('Resume the initial sync')
failPoint.off();
jsTestLog('Pause index build on initial sync node');
fpIndexInit.wait();
jsTestLog('Resume index build on sync source to finish');
fpIndexSrc.off();
awaitIndex();
jsTestLog('Resume index build on initial sync node to finish');
fpIndexInit.off();
jsTestLog('Wait for both nodes to be up-to-date');
rst.awaitSecondaryNodes();
rst.awaitReplication();
rst.checkReplicatedDataHashes();
rst.checkOplogs();
rst.stopSet();
})();