'use strict'

var Path = require('path')
var spawn = require('child_process').spawn
var version = require('version')

var Log = require(Path.join(__base, 'src/worker/log.js'))
var LogWorker = new Log({
  module: 'Update'
})

var pkg = require(Path.join(__base, 'package.json'))

function Update (cb) {
  version.fetch('lunik-torrent', function (error, version) {
    if (error) {
      LogWorker.error(error)
      process.exit(1)
    } else {
      if (version === pkg.version) {
        LogWorker.info('You have the last version: ' + version)
        cb()
      } else {
        LogWorker.warning("You don't have the last version: " + version)
        if (__config.autoUpdate) {
          LogWorker.info('Auto updating the app.')
          var pull = spawn('git', ['pull'])
          pull.stdout.on('data', (data) => {
            LogWorker.info(data)
          })
          pull.stderr.on('data', (data) => {
            LogWorker.error(data)
          })
          pull.on('exit', (code) => {
            if (code) {
              LogWorker.error('Git pull fail with code: ' + code)
              process.exit(1)
            }
            var checkout = spawn('git', ['checkout', 'tags/' + version])
            checkout.stdout.on('data', (data) => {
              LogWorker.info(data)
            })
            checkout.stderr.on('data', (data) => {
              LogWorker.error(data)
            })
            checkout.on('exit', (code) => {
              if (code) {
                LogWorker.error('Git pull fail with code: ' + code)
                process.exit(1)
              }
              LogWorker.info('Update to ' + version + 'succeed.')
              cb()
            })
          })
        } else {
          LogWorker.warning('Auto update is disabled.')
          cb()
        }
      }
    }
  })
}
module.exports = Update

@@ -1128,472 +1128,8 @@
   %7D%0A
-            var checkout = spawn('git', %5B'checkout', 'tags/' + version%5D)%0A            checkout.stdout.on('data', (data) =%3E %7B%0A              LogWorker.info(data)%0A            %7D)%0A            checkout.stderr.on('data', (data) =%3E %7B%0A              LogWorker.error(data)%0A            %7D)%0A            checkout.on('exit', (code) =%3E %7B%0A              if (code) %7B%0A                LogWorker.error('Git pull fail with code: ' + code)%0A                process.exit(1)%0A              %7D%0A  
     
@@ -1204,30 +1204,13 @@
     
-  
 cb()%0A
-            %7D)%0A
     

remove checkout