let debug = require('./debug')('indexd:resync')
let parallel = require('run-parallel')
let rpcUtil = require('./rpc')

// recursively calls connectBlock(id) until `bitcoind[id].next` is falsy
function connectBlock (rpc, indexd, id, height, callback) {
  debug(`Connecting ${id} @ ${height}`)

  indexd.connect(id, height, (err, nextblockhash) => {
    if (err) return callback(err)

    debug(`Connected ${id} @ ${height}`)
    if (!nextblockhash) return callback()

    // recurse until next is falsy
    connectBlock(rpc, indexd, nextblockhash, height + 1, callback)
  })
}

function disconnectBlock (indexd, id, callback) {
  debug(`Disconnecting ${id}`)

  indexd.disconnect(id, (err) => {
    if (err) return callback(err)

    debug(`Disconnected ${id}`)
    callback()
  })
}

module.exports = function resync (rpc, indexd, callback) {
  debug('fetching bitcoind/indexd tips')

  parallel({
    bitcoind: (f) => rpcUtil.tip(rpc, f),
    indexd: (f) => indexd.tip(f)
  }, (err, tips) => {
    if (err) return callback(err)

    // Step 0, genesis?
    if (!tips.indexd) {
      debug('genesis')
      return rpcUtil.blockIdAtHeight(rpc, 0, (err, genesisId) => {
        if (err) return callback(err)

        connectBlock(rpc, indexd, genesisId, 0, callback)
      })
    }

    // Step 1, equal?
    debug('...', tips)
    if (tips.bitcoind === tips.indexd) return callback()

    // else, Step 2, is indexd behind? [bitcoind has indexd tip]
    rpcUtil.headerJSON(rpc, tips.indexd, (err, common) => {
      // not in bitcoind chain? [forked]
      if (
        (err && err.message === 'Block not found') ||
        (!err && common.confirmations === -1)
      ) {
        debug('indexd is forked')
        return disconnectBlock(indexd, tips.indexd, (err) => {
          if (err) return callback(err)

          resync(rpc, indexd, callback)
        })
      }
      if (err) return callback(err)

      // indexd is behind
      debug('bitcoind is ahead')
      connectBlock(rpc, indexd, common.nextblockhash, common.height + 1, callback)
    })
  })
}

@@ -878,16 +878,182 @@
 tips')%0A%0A
+  function trySyncFrom (id, height) %7B%0A    connectBlock(rpc, indexd, id, height, (err) =%3E %7B%0A      if (err) return callback(err)%0A      callback(null, true)%0A    %7D)%0A  %7D%0A%0A
   parall
@@ -1378,34 +1378,20 @@
     
-connectBlock(rpc, indexd, 
+trySyncFrom(
 gene
@@ -1398,26 +1398,16 @@
 sisId, 0
-, callback
 )%0A      
@@ -1508,32 +1508,43 @@
 return callback(
+null, false
 )%0A%0A    // else, 
@@ -1540,14 +1540,8 @@
   //
- else,
  Ste
@@ -1564,16 +1564,26 @@
 ehind? %5B
+aka, does 
 bitcoind
@@ -1585,17 +1585,22 @@
 coind ha
-s
+ve the
  indexd 
@@ -1679,37 +1679,16 @@
 / no
-t in bitcoind chain
 ? 
-%5B
 forked
-%5D
 %0A   
@@ -2047,16 +2047,21 @@
       //
+ yes,
  indexd 
@@ -2113,34 +2113,20 @@
     
-connectBlock(rpc, indexd, 
+trySyncFrom(
 comm
@@ -2156,34 +2156,24 @@
 n.height + 1
-, callback
 )%0A    %7D)%0A  %7D

refactor comments and common code