#!/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.

InsertOrUpdate() {
#InsertOrUpdate table set_key set_value [set_key set_value […]] <	where_key where_value
#									[where_key where_value
#									[…]]
	local			\
		table="$1"	\
		argument	\
		key		\
		keys		\
		set_keys	\
		set_values	\
		value		\
		values		\
		what		\
		results
	shift
	# Parse positional args as alternating key/value pairs for the SET
	# clause
	what=key
	for argument
	do
		case $what in
			key)
				set_keys+=( "$argument" )
				what=value
			;;
			value)
				set_values+=( "$argument" )
				what=key
			;;
		esac
	done
	# Read WHERE conditions from stdin
	while read key value
	do
		keys+=( "$key" )
		values+=( "$value" )
	done
	# Check if a matching row exists using the WHERE keys
	if results=$(
		Select "$table" ${keys[0]} < <(
			for key in ${!keys[@]}
			do
				echo "${keys[$key]}" = "${values[$key]}"
			done
		)
	)
	then
		# Row exists: update it with the SET values
		Update "$table" "$@" < <(
			for key in ${!keys[@]}
			do
				echo "${keys[$key]}" = "${values[$key]}"
			done
		)
	else
		# Row not found: insert combining SET columns and WHERE-match
		# columns
		results=$(
			Insert "$table" < <(
				for key in ${!set_keys[@]}
				do
					echo "${set_keys[$key]}" "${set_values[$key]}"
				done
				for key in ${!keys[@]}
				do
					echo "${keys[$key]}" "${values[$key]}"
				done
			)
		)
	fi
	echo "$results"
}
