balena-supervisor/app.coffee

84 lines
2.0 KiB
CoffeeScript
Raw Normal View History

2013-07-18 10:40:35 +00:00
fs = require('fs')
async = require('async')
request = require('request')
2013-07-18 23:31:42 +00:00
getuid = require('getuid')
2013-07-18 11:07:39 +00:00
{exec} = require('child_process')
2013-07-18 10:40:35 +00:00
API_ENDPOINT = 'http://paras.rulemotion.com:1337'
2013-07-18 23:31:42 +00:00
HAKI_PATH = '/home/haki'
2013-07-18 10:40:35 +00:00
try
2013-07-18 11:35:21 +00:00
state = require('./state.json')
2013-07-18 10:40:35 +00:00
catch e
console.error(e)
process.exit()
bootstrapTasks = [
2013-07-18 11:07:39 +00:00
# get config from extra partition
2013-07-18 10:40:35 +00:00
(callback) ->
try
callback(null, require('/mnt/config.json'))
catch error
callback(error)
2013-07-18 13:02:45 +00:00
# bootstrapping
2013-07-18 10:40:35 +00:00
(config, callback) ->
request.post("#{API_ENDPOINT}/associate", {
2013-07-18 23:31:42 +00:00
json:
user: config.id
2013-07-18 10:40:35 +00:00
}, (error, response, body) ->
if error
return callback(error)
2013-07-18 23:31:42 +00:00
if typeof body isnt 'object'
callback(body)
2013-07-18 10:40:35 +00:00
state.virgin = false
state.uuid = body.uuid
state.giturl = body.giturl
2013-07-18 10:40:35 +00:00
2013-07-18 23:31:42 +00:00
console.log state
2013-07-18 11:37:04 +00:00
fs.writeFileSync('state.json', JSON.stringify(state))
2013-07-18 10:40:35 +00:00
2013-07-18 11:07:39 +00:00
fs.writeFileSync('/etc/openvpn/ca.crt', body.ca)
fs.writeFileSync('/etc/openvpn/client.crt', body.cert)
fs.writeFileSync('/etc/openvpn/client.key', body.key)
fs.appendFileSync('/etc/openvpn/client.conf', "remote #{body.vpnhost} #{body.vpnport}")
2013-07-18 10:40:35 +00:00
callback(null)
)
]
2013-07-18 11:07:39 +00:00
stage1Tasks = [
(callback) -> async.waterfall(bootstrapTasks, callback)
(callback) -> exec('systemctl start openvpn@client', callback)
(callback) -> exec('systemctl enable openvpn@client', callback)
2013-07-18 23:31:42 +00:00
(callback) ->
process.setuid(getuid('haki'))
process.chdir(HAKI_PATH)
fs.mkdir('hakiapp', callback)
(callback) -> exec('git init', cwd: 'hakiapp', callback)
(callback) -> exec("git remote add origin #{state.giturl}", cwd: 'hakiapp', callback)
2013-07-18 11:07:39 +00:00
]
stage2Tasks = [
2013-07-18 23:31:42 +00:00
(callback) ->
process.setuid(getuid('haki'))
process.chdir(HAKI_PATH)
fs.mkdir('hakiapp', callback)
(callback) -> async.forever([
(callback) -> exec('git pull', cwd: 'hakiapp', callback)
(callback) -> exec('npm install', cwd: 'hakiapp', callback)
(callback) -> exec('foreman start', cwd: 'hakiapp', callback)
])
]
2013-07-18 23:31:42 +00:00
if state.virgin
async.series(stage1Tasks, (error, results) ->
if (error)
console.error(error)
else
console.log('Bootstrapped')
)