 					console.log('Joined! Exiting.')
 					retryCallback()
 				.catch (err) ->
-					startServer(wifi)
-
+					connectOrStartServer(wifi, retryCallback)
 			else
 				console.log('Already connected')
 				retryCallback()

bodyParser = require('body-parser')
iptables = Promise.promisifyAll(require('./iptables'))
spawn = require('child_process').spawn
os = require('os')
async = require('async')


					throw err if err?
					console.log('Server listening')

connectOrStartServer = (wifi, retryCallback) ->
	if connectionsFromFile?
		console.log('Trying to join previously known networks')
		Promise.each connectionsFromFile, (conn) ->
			wifi.joinAsync(conn.ssid, conn.passphrase)
			.then ->
				console.log('Joined! Exiting.')
				retryCallback()
			.catch(ignore)
		.then ->
			startServer(wifi)
	else
		startServer(wifi)

saveToFile = (ssid, passphrase) ->
	if connectionsFromFile?
		connectionsFromFile.push({ ssid, passphrase })
	else
		connectionsFromFile = [ { ssid, passphrase } ]
	return new Promise (resolve, reject) ->
		fs.writeFile connectionFile, JSON.stringify(connectionsFromFile), (err) ->
			return reject(err) if err?
			exec 'sync', (err) ->
				reject(err) if err?
				resolve()

console.log('Starting node connman app')
manageConnection = (retryCallback) ->
	connman.initAsync()
