const path = require('path')
const untildify = require('untildify')
const startup = require('user-startup')
const conf = require('../conf')
const pidFile = require('../pid-file')
const debug = require('../utils/debug')

module.exports = {
  start,
  stop
}

// Start daemon in background
function start () {
  const node = process.execPath
  const daemonFile = path.join(__dirname, '../daemon')
  const daemonLog = path.resolve(untildify('~/.hotel/daemon.log'))
  const startupFile = startup.getFile('hotel')

  debug(`creating ${startupFile}`)
  startup.create('hotel', node, [daemonFile], daemonLog)

  console.log(`Started http://localhost:${conf.port}`)
}

// Stop daemon using killURL
function stop () {
  startup.remove('hotel')
  const pid = pidFile.read()
  if (pid) process.kill(pid)
  console.log('Stopped')
}

@@ -679,15 +679,11 @@
 ing 
-killURL
+PID
 %0Afun
@@ -768,25 +768,100 @@
 id) 
-process.kill(pid)
+%7B%0A    try %7B%0A      // May fail in some cases%0A      process.kill(pid)%0A    %7D catch (err) %7B%7D%0A  %7D
 %0A  c

Handle process.kill error