#!/usr/bin/env bash
# Make sure the current directory is the location of this script to simplify matters
cd "$(dirname $(readlink -f $0))";
################
### Settings ###
################

# The name of this project
project_name="Msc Summer Project";

# The path to the lantern build engine git submodule
lantern_path="./lantern-build-engine";

###
# Custom Settings
###

# Put any custom settings here.


###############################################################################

# Check out the lantern git submodule if needed
if [ ! -f "${lantern_path}/lantern.sh" ]; then git submodule update --init "${lantern_path}"; fi

source "${lantern_path}/lantern.sh";

if [[ "$#" -lt 1 ]]; then
	echo -e "${FBLE}${project_name}${RS} build script";
	echo -e "    by Starbeamrainbowlabs";
	echo -e "${LC}Powered by the lantern build engine, v${version}${RS}";
	echo -e "";
	echo -e "${CSECTION}Usage${RS}";
	echo -e "    ./build ${CTOKEN}{action}${RS} ${CTOKEN}{action}${RS} ${CTOKEN}{action}${RS} ...";
	echo -e "";
	echo -e "${CSECTION}Available actions${RS}";
	echo -e "    ${CACTION}setup${RS}        - Perform initial setup";
	echo -e "    ${CACTION}render${RS}       - Render the report";
	echo -e "    ${CACTION}server-ttn${RS}   - Execute the Node.js TTN receiver.";
	echo -e "";
	
	exit 1;
fi

###############################################################################

# Toggles commenting and uncommenting lines in a file that contain a specific 
# substring. Checks for word boundaries either side of the substring.
# From https://stackoverflow.com/a/24901636/1460422
# $1 - Filename
# $2 - Search string
comment_toggle() {
	filename="${1}";
	search_string="${2}";
	
	awk -v commentId='//' -v word="${search_string}" '
	  $0 ~ "(^|[[:punct:][:space:]])" word "($|[[:punct:][:space:]])" { 
	    if (match($0, "^[[:space:]]*" commentId))
	      $0 = substr($0, RSTART + RLENGTH)
	    else
	      $0 = commentId $0
	  } 
	  { print }' "${filename}" > tmpfile.$$ && mv tmpfile.$$ "${filename}"
}

task_setup() {
	stage_begin "Setting up";
	
	task_begin "Checking Environment";
	check_command git true;
	check_command awk true;
	check_command pdflatex true;
	check_command bibtex true;
	task_end $?;
	
	task_begin "Initialising submodules";
	git submodule update --init;
	task_end $?;
	
	task_begin "Preconfiguring libraries";
	config_file_directory="./iot/libraries/arduino-lmic/src/lmic/";
	config_file_name="config.h";
	cd "${config_file_directory}";
	git reset --hard;
	# Disable OTAA
	comment_toggle "${config_file_name}" "#define DISABLE_JOIN";
	# Disable class b stuff
	comment_toggle "${config_file_name}" "#define DISABLE_PING";
	comment_toggle "${config_file_name}" "#define DISABLE_BEACONS";
	# Disable other misc. stuff we're not likely to use
	comment_toggle "${config_file_name}" "#define DISABLE_MCMD_DCAP_REQ"; # Duty cycle cap - won't  work anyway 'cause we're shutting down in between
	comment_toggle "${config_file_name}" "#define DISABLE_MCMD_DN2P_SET"; # Receiving stuff
	
	# echo "#define DISABLE_JOIN" >>"${config_file_name}";
	# echo "#define DISABLE_PING" >>"${config_file_name}";
	# echo "#define DISABLE_BEACONS" >>"${config_file_name}";
	cd -;
	task_end $?;
	
	task_begin "Installing server dependencies";
	cd server;
	npm install;
	cd ..;
	exit_code="${?}";
	task_end ${exit_code};
	
	stage_end 0;
}

task_server-ttn() {
	execute node --experimental-modules ./server/index.mjs ttn-app-server;
}

###############################################################################

task_render() {
	_render-latex-pdf "Reports/Initial-Report/Initial-Report.tex";
}

# $1 - Location of top-level LaTeX file
_render-latex-pdf() {
	if [[ ! -f "$1" ]]; then
		task_end 1 "Error: Couldn't find '$1'";
	fi
	
	task_begin "Entering directory";
	latex_filename="$(basename "$1")";
	latex_directory="$(dirname "$1")";
	
	execute cd "${latex_directory}";
	execute echo "${PWD}";
	task_end $? "Failed to enter directory (does it exist?)";
	
	task_begin "Cleaning up";
	find -iname "*.aux" -delete; # Ref: https://tex.stackexchange.com/q/381057
	find -iname "*.bbl" -delete;
	find -iname "*.blg" -delete;
	find -iname "*.out" -delete;
	task_end $? "Error: Failed to clean up after last build";
	
	# task_begin "Rendering images";
	# # FUTURE: Do this in paralell?
	# for svg_filename in $(find "images/" -type f -iname "*.svg"); do
	# 	execute inkscape -e ${svg_filename%%.svg}.png ${svg_filename};
	# 	exit_code=$?;
	# 	[[ "${exit_code}" -eq 0 ]] || break;
	# done
	# task_end "${exit_code}";
	
	task_begin "Building Report";
	set -e;
	execute pdflatex --output-directory=. "${latex_filename}";
	execute bibtex "${latex_filename%.*}";
	execute pdflatex --output-directory=. "${latex_filename}";
	execute pdflatex --output-directory=. "${latex_filename}";
	execute bibtex "${latex_filename%.*}";
	execute pdflatex --output-directory=. "${latex_filename}";
	execute pdflatex --output-directory=. "${latex_filename}";
	set +e;
	task_end $? "Error: Failed to build report";
	
	task_begin "Moving report";
	execute mv *.pdf ..;
	task_end $? "Failed to move report";
	
	cd -;
}


###############################################################################

tasks_run $@;