#!/bin/bash

# This script allows variable keys inside SQL files to be replaced by
# corresponding values, when the keys are surrounded by <>.
#
# Usage:
#   inject_variables.sh FILE -v KEY VALUE [-v KEY2 VALUE2[, ...]] [OUTFILE]
#
# For example, if FILE contains
#   SELECT <COLUMN1>, <COLUMN2> FROM TABLE;
# then
#   inject_variables.sh FILE -v COLUMN1 artistid -v COLUMN2 artistname OUTFILE
# will create OUTFILE with contents
#   SELECT artistid, artistname FROM TABLE;
#
# Use cases include injecting AWS credentials and schema names when setting
# grants on new tables. If an output file is not provided, the input file
# is overwritten.


# Print usage and exit without success when no arguments provided
if [ $# = 0 ]; then
	echo Usage: inject_variables.sh FILE -v KEY VALUE [-v KEY2 VALUE2[, ...]] [OUTFILE]
	exit 1
fi

# Parse inputs
file=$1
shift

outfile=$file
keys=()
values=()
while (( $# > 0 )); do
	if [ $1 = '-v' ]; then
		keys+=($2)
		values+=($3)
		shift 3
	else
		outfile=$1
		shift 1
	fi
done

# Replace
tempfile=$file.tmp
cp $file $tempfile
for ((i = 0; i < ${#keys[@]}; i++)); do
	sed "s|<${keys[i]}>|${values[i]}|g" $tempfile > $outfile
	cp $outfile $tempfile
done
rm $tempfile
