#!/usr/bin/env node

require('../lib/environment-helper')
const hdkey = require('ethereumjs-wallet/hdkey')
const hkdf = require('futoin-hkdf')
const db = require('../lib/db')
const _ = require('lodash/fp')
const mnemonicHelpers = require('../lib/mnemonic-helpers')

const pify = require('pify')
const fs = pify(require('fs'))
const os = require('os')

const MNEMONIC_PATH = process.env.MNEMONIC_PATH

const defaultPrefixPath = "m/44'/60'/1'/0'"
const paymentPrefixPath = "m/44'/60'/0'/0'"

const address = process.argv[2]

if (!MNEMONIC_PATH) {
  console.error(`Unable to fetch mnemonic from your account!`)
  process.exit(1)
}

if (!address) {
  console.log('Usage: lamassu-eth-recovery <cash-out address>')
  process.exit(2)
}

function run (address) {
  Promise.all([fetchMnemonic(), searchForHdIndex(address)])
    .then(([mnemonic, hdIndex]) => {
      try {
        const prefix = !_.isNil(hdIndex) ? paymentPrefixPath : defaultPrefixPath
        console.log(`Private key: `, defaultHdNode(mnemonic, prefix).deriveChild(hdIndex).getWallet().getPrivateKeyString())
        process.exit(0)
      } catch (err) {
        console.error(`Error while retrieving private key!`)
        process.exit(3)
      }
    })
}

function searchForHdIndex (address) {
  const sql = `SELECT hd_index FROM cash_out_txs WHERE to_address = $1`
  return db.oneOrNone(sql, [address])
    .then(result => _.get('hd_index', result))
}

function fetchMnemonic () {
  return fs.readFile(MNEMONIC_PATH, 'utf8')
    .then(mnemonic => computeSeed(mnemonic))
}

function computeSeed (seed) {
  const masterSeed = mnemonicHelpers.toEntropyBuffer(seed)
  return hkdf(masterSeed, 32, { salt: 'lamassu-server-salt', info: 'wallet-seed' })
}

function defaultHdNode (masterSeed, prefix) {
  if (!masterSeed) throw new Error('No master seed!')
  const key = hdkey.fromMasterSeed(masterSeed)
  return key.derivePath(prefix)
}

run(address)
