const path = require('path');
const mkdirp = require('mkdirp');
const emptyDir = require('empty-dir');
const spawn = require('child_process').spawn;

exports.initdb = function (dbPath, callback) {
  var opts = {};
  if (arguments.length === 3) {
    opts = arguments[1];
    callback = arguments[2];
  }
  if (!dbPath) {
    throw new Error('You must specify a directory to initialize.');
  }
  var dir = path.resolve(dbPath);
  mkdirp.sync(dir);
  if (!emptyDir.sync(dir)) {
    throw new Error('Refusing to init in non-empty directory.');
  }
  var init = spawn('./pgsql/bin/initdb', ['-D', dir]);
  if (opts.verbose === true) {
    init.stdout.on('data', function (data) {
      process.stdout.write(data);
    });
    init.stderr.on('data', function (data) {
      process.stderr.write(data.toString());
    });
  }
  init.on('close', function (code) {
    callback(code);
  });
};

exports.start = function (dbPath, opts) {
  opts = opts || {};
  var dir = path.resolve(dbPath);
  var start = spawn('./pgsql/bin/postgres', ['-D', dir]);
  start.stdout.on('data', function (data) {
    process.stdout.write(data);
  });
  start.stderr.on('data', function (data) {
    process.stderr.write(data.toString());
  });
};
