<commit_before>Promise = require('bluebird')
connman = Promise.promisifyAll(require('connman-simplified')())
express = require('express')
app = express()
bodyParser = require('body-parser')
iptables = Promise.promisifyAll(require('./iptables'))
spawn = require('child_process').spawn
exec = require('child_process').exec
os = require('os')
async = require('async')

config = require('./wifi.json')
ssid = process.env.PORTAL_SSID or config.ssid
passphrase = process.env.PORTAL_PASSPHRASE or config.passphrase
port = process.env.PORTAL_PORT or config.port

server = null
ssidList = null
dnsServer = null

connectionFile = '/data/connections.json'
connectionsFromFile = null
if fs.existsSync(connectionFile)
	connectionsFromFile = require(connectionFile)

ignore = ->

getIptablesRules = (callback) ->
	async.retry {times: 100, interval: 100}, (cb) ->
		Promise.try ->
			os.networkInterfaces().tether[0].address
		.nodeify(cb)
	, (err, myIP) ->
		return callback(err) if err?
		callback null, [
				table: 'nat'
				rule: 'PREROUTING -i tether -j TETHER'
			,
				table: 'nat'
				rule: "TETHER -p tcp --dport 80 -j DNAT --to-destination #{myIP}:#{port}"
			,
				table: 'nat'
				rule: "TETHER -p tcp --dport 443 -j DNAT --to-destination #{myIP}:#{port}"
			,
				table: 'nat'
				rule: "TETHER -p udp --dport 53 -j DNAT --to-destination #{myIP}:53"
		]


startServer = (wifi) ->
	console.log('Getting networks list')
	wifi.getNetworksAsync().then (list) ->
		ssidList = list
		wifi.openHotspotAsync(ssid, passphrase)
	.then ->
		console.log('Hotspot enabled')
		dnsServer = spawn('named', ['-f'])
		getIptablesRules (err, iptablesRules) ->
			throw err if err?
			iptables.appendManyAsync(iptablesRules)
			.then ->
				console.log('Captive portal enabled')
				server = app.listen port, (err) ->
					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) -><commit_msg>Clean up saveToFile<commit_after>Promise = require('bluebird')
connman = Promise.promisifyAll(require('connman-simplified')())
express = require('express')
app = express()
bodyParser = require('body-parser')
iptables = Promise.promisifyAll(require('./iptables'))
spawn = require('child_process').spawn
exec = require('child_process').exec
os = require('os')
async = require('async')
fs = Promise.promisifyAll(require('fs'))

config = require('./wifi.json')
ssid = process.env.PORTAL_SSID or config.ssid
passphrase = process.env.PORTAL_PASSPHRASE or config.passphrase
port = process.env.PORTAL_PORT or config.port

server = null
ssidList = null
dnsServer = null

connectionFile = '/data/connections.json'
connectionsFromFile = null
if fs.existsSync(connectionFile)
	connectionsFromFile = require(connectionFile)

ignore = ->

getIptablesRules = (callback) ->
	async.retry {times: 100, interval: 100}, (cb) ->
		Promise.try ->
			os.networkInterfaces().tether[0].address
		.nodeify(cb)
	, (err, myIP) ->
		return callback(err) if err?
		callback null, [
				table: 'nat'
				rule: 'PREROUTING -i tether -j TETHER'
			,
				table: 'nat'
				rule: "TETHER -p tcp --dport 80 -j DNAT --to-destination #{myIP}:#{port}"
			,
				table: 'nat'
				rule: "TETHER -p tcp --dport 443 -j DNAT --to-destination #{myIP}:#{port}"
			,
				table: 'nat'
				rule: "TETHER -p udp --dport 53 -j DNAT --to-destination #{myIP}:53"
		]


startServer = (wifi) ->
	console.log('Getting networks list')
	wifi.getNetworksAsync().then (list) ->
		ssidList = list
		wifi.openHotspotAsync(ssid, passphrase)
	.then ->
		console.log('Hotspot enabled')
		dnsServer = spawn('named', ['-f'])
		getIptablesRules (err, iptablesRules) ->
			throw err if err?
			iptables.appendManyAsync(iptablesRules)
			.then ->
				console.log('Captive portal enabled')
				server = app.listen port, (err) ->
					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) ->
	connectionsFromFile ?= []
	connectionsFromFile.push({ ssid, passphrase })
	fs.openAsync(connectionFile, 'w')
	.tap (fd) ->
		fs.writeAsync(fd, JSON.stringify(connectionsFromFile))
	.tap (fd) ->
		fs.fsyncAsync(fd)
	.then (fd) ->
		fs.closeAsync(fd)

console.log('Starting node connman app')
manageConnection = (retryCallback) ->
{'fraction_non_alphanumeric': 0.14772514510391313, 'fraction_numerical': 0.00599138738064033, 'mean_word_length': 4.077946768060836, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 43, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4842861', 'n_tokens_mistral': 2034, 'n_tokens_neox': 1811, 'n_words': 419}