#!/bin/bash

# Copyright © 2012-2026 ScriptFanix
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# A copy of the GNU General Public License v3 is includded in the LICENSE file
# at the root of the project.

InsertIfUnset() {
#InsertIfUnset table [no_id] < key value \n key value
#
# If no_id is set to a non-zero value, the function will not return the
# auto-assigned row ID of the inserted row. 
	local			\
		table="$1"	\
		no_id="${2:-0}"	\
		column		\
		key		\
		keys		\
		results		\
		value		\
		values
	# Read all key-value pairs from stdin into parallel arrays
	while read key value
	do
		keys+=( "$key" )
		values+=( "$value" )
	done
	# Choose which column to return: first key column if no_id, else 'id'
	if (( no_id ))
	then
		column="${keys[0]}"
	else
		column='id'
	fi
	# Check if a matching row already exists
	if ! results=$(
		Select "$table" "$column" < <(
			for key in ${!keys[@]}
			do
				# Strip ::AtOM:FT:: for WHERE comparison
				echo "${keys[$key]}" =			\
					"${values[$key]//::AtOM:FT::}"
			done
		)
	)
	then
		# Row not found: insert it and return the new id
		results=$(
			Insert "$table" < <(
				for key in ${!keys[@]}
				do
					echo "${keys[$key]}" "${values[$key]}"
				done
			)
		)
	fi
	echo "$results"
}
