#!/usr/bin/env bash
set -x

#serial:
#	additionalPorts:
#	- /tmp/printer
#	baudrate: 250000
#	disconnectOnErrors: false
#	port: /tmp/printer

OCTO_PRINTER="/tmp/printer"
SERIAL_DEVICE=${OCTO_PRINTER}
JSON_FILE="config.json"
YAML_FILE="config.yaml"
#BASEDIR="/opt/octoprint/etc/"
BASEDIR="/tmp/"
WORKDIR="/tmp"

declare -A OCTO_OPT
OCTO_OPT[1]='.serial.additionalPorts = "/tmp/printer" | .serial.baudrate = 250000 | .serial.disconnectOnErrors = "true" | .serial.port = "/tmp/printer" '

#OCTO_OPT[1]=".serial.additionalPorts = "${OCTO_PRINTER}" 
#| .serial.baudrate = 250000 
#| .serial.disconnectOnErrors = "false" 
#| .serial.port = "${OCTO_PRINTER}" "



if [ ! -f ${WORKDIR}/${JSON_FILE} ]
then
	echo "{}" > ${WORKDIR}/${JSON_FILE}
else
	echo "${WORKDIR}/${JSON_FILE} exists."
fi

# Count through the number of array elements, using ${#
# looking for one missing.
for ((i = 1; i < ${#OCTO_OPT[@]}; ++i)); do
	if [ -z "${OCTO_OPT[$i]}" ]; then
		echo Error: $i missing.
		exit 1
	fi
done

# Work through each array element, using ${!.
# regardless how it's spelled.
for i in "${!OCTO_OPT[@]}"; do
	OPTION="${OCTO_OPT[$i]}"
	jq "${OPTION}" ${WORKDIR}/${JSON_FILE} > ${WORKDIR}/${JSON_FILE}.new && \
		mv -b ${WORKDIR}/${JSON_FILE}.new ${WORKDIR}/${JSON_FILE}
	yq -y . ${WORKDIR}/${JSON_FILE} > ${BASEDIR}/${YAML_FILE}
done
