# File: buildEddystonePluginJS.rb
#
# Build script for Evothings Eddystone plugin JavaScript file.
#
# Resulting output file is eddystone-plugin.js, which contains code
# for the Eddystone JS API and the required support functions.
#
# Note that this repo contains a pre-built version of eddystone-plugin.js.
# The plugin works out-of-the-box and you only need to rebuild this file
# when updating or developing the plugin, normally done by plugin maintainers.

require "fileutils"

include FileUtils::Verbose

### File helpers

def fileRead(filePath)
	File.open(filePath, "r") {
		|f|
		s = f.read
		if (RUBY_VERSION >= "1.9")
			return s.force_encoding("UTF-8")
		else
			return s
		end
	}
end

def fileWrite(destFile, content)
	File.open(destFile, "w") { |f| f.write(content) }
end

### Merge library files

def mergeFiles
	# Base path for JS files is the evothings-examples repo, which
	# should be checked out next to this repo when building.
	libsPath = "../evothings-libraries/libs/evothings/"

	# Paths to JS files.
	utiljs = fileRead(libsPath + "util/util.js")
	easyblejs = fileRead(libsPath + "easyble/easyble.js")
	eddystonejs = fileRead(libsPath + "eddystone/eddystone.js")
	evothingsbasejs = fileRead("js/evothings-base.js")
	eddystoneexportsjs = fileRead("js/eddystone-exports.js")

	# File separator.
	fileSep = "\n\n// --------------------------------------------------\n\n\n"

	# Concatenate files.
	eddystonepluginjs =
		"// This file was generated by buildEddystonePluginJS.rb" + fileSep +
		evothingsbasejs + fileSep +
		utiljs  + fileSep +
		easyblejs + fileSep +
		eddystonejs + fileSep +
		eddystoneexportsjs

	# Replace evothings.loadScripts and evothings.loadScript
	# with dummy function to disable async script loading since
	# we have all scripts in one file now.
	eddystonepluginjs = eddystonepluginjs
		.gsub("evothings.loadScripts", "evothings.__NOOP_FUN__")
		.gsub("evothings.loadScript", "evothings.__NOOP_FUN__")

	# Write out plugin JS file.
	fileWrite("js/eddystone-plugin.js", eddystonepluginjs)
end

### Call main function

mergeFiles
