#!/bin/bash

if [ ! -d .git ];
then
	echo "in a git directory plz"
	exit 0
fi

T="$(date +%s)"
SQLSERVER='USSC10050'
SQLDATABASE='lumedQA'
SQLDATABASE2='QA_IntegrationTests'
# CONNECTIONSTRING="metadata=res:\/\/*\/CommonEntities.csdl|res:\/\/*\/CommonEntities.ssdl|res:\/\/*\/CommonEntities.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data source=$SQLSERVER;Initial Catalog=$SQLDATABASE;Integrated Security=True;Max Pool Size=200;MultipleActiveResultSets=True;App=EntityFramework&quot;"
CONNECTIONSTRING="Data source=$SQLSERVER;Initial Catalog=$SQLDATABASE;Integrated Security=True;Max Pool Size=200;MultipleActiveResultSets=True;App=EntityFramework"
CONNECTIONSTRING2="Data source=$SQLSERVER;Initial Catalog=$SQLDATABASE2;Integrated Security=True;Max Pool Size=200;MultipleActiveResultSets=True;App=EntityFramework"

NARROW=${1:-''}

REPO="$(pwd | xargs cygpath --windows | sed 's/\\/\\\\/g')"
REPOJSON="$(pwd | xargs cygpath --windows | sed 's/\\/\\\\\\\\/g')"

echo "$CONNECTIONSTRING"

for FILE in $(find -iname "app.config" -o -iname "web.config" -o -iname "appsettings.json" | grep "$NARROW" )
do
	if grep -qi "metadata=res" "$FILE"
	then
		printf "$FILE";
		printf "."

		git update-index -q --assume-unchanged $FILE
		printf "."

		if grep -qi "IntegrationTests" "$FILE"
		then
			sed -i "s/Data source=.*App=EntityFramework/$CONNECTIONSTRING2/IM" $FILE;
		else
			sed -i "s/Data source=.*App=EntityFramework/$CONNECTIONSTRING/IM" $FILE;
		fi

		if [[ "$FILE" == *.config ]]; then
		    sed -i "s=%LUMEDPROJECT_GIT%=$REPO=IM" $FILE;
		    printf "."
		elif [[ "$FILE" == *.json ]]; then
		    sed -i "s=%LUMEDPROJECT_GIT%=$REPOJSON=IM" $FILE;
		    printf "_"
		else
		    printf "x"
		fi
        
		printf "\n"
	fi
done

TT="$(($(date +%s)-T))"
echo "done in ${TT} sec"

