#!/bin/bash

set -e

# Import external functions
chmod +x ./devops/PipeLines/functions.sh
./devops/PipeLines/functions.sh

GetAppName appName
echo "Continuous integration for ${appName} starting..."

GetCiCdSettings allPublishable noPublishable
if [ "${noPublishable}" == "1" ] ;
then
    echo ""
    echo "Tips: No services need to be cied."
else
    declare solutionName=($(grep -oP '(?<=SolutionName>)[^<]+' "devops/app.props"))
    dotnet build ${solutionName}	 

	echo "Please check the version of each microservice carefully !!!"
	declare major=($(grep -oP '(?<=VersionMajor>)[^<]+' "build/version.props"))
	declare minor=($(grep -oP '(?<=VersionMinor>)[^<]+' "build/version.props"))
	declare patch=($(grep -oP '(?<=VersionPatch>)[^<]+' "build/version.props"))
	declare version=${major}.${minor}.${patch}

	declare registryUserName=($(grep -oP '(?<=ImageUserName>)[^<]+' "build/deploy.props"))

	declare publishOutputDir=./publish

	rm -fr ${publishOutputDir}
	mkdir -p ${publishOutputDir}

	function CI()
	{
		declare publishable=$1
		declare imagename=$2

		echo ""
		if [ "${publishable}" == "1" ]; 
		then
			declare imagefullname=${RegistryHost}/${registryUserName}/${imagename}:${version}
			declare publishFile=$3

			echo "begin delivery of master branch for ${imagename}..."
			mkdir -p ${publishOutputDir}/${imagename}
			dotnet publish ${publishFile} -o ../../publish/${imagename} -c release --no-restore  
			docker build -t ${imagefullname} ${publishOutputDir}/${imagename}
			docker push ${imagefullname}
			echo "delivery of master branch for ${imagename}:${version} has been successful."
		else
			echo "Tips: master branch for ${imagename}:${version} will not be cied!!!"
		fi
	}

	declare services=$(ls -l src/services | awk 'NR>1')
	declare servicePrefix=""
	declare serviceName=""
	declare isPublishable="0"
	for service in ${services}
	do
	  servicePrefix=($(echo ${service} | awk '{print $9}')) 
	  isPublishable=($(grep -oP "(?<=${servicePrefix}Publishable>)[^<]+" "/tmp/cicd.props"))
	  GetServiceName "${servicePrefix}" serviceName
	  CI ${isPublishable} "${servicePrefix}" "./src/${servicePrefix}/${serviceName}.csproj"
	done
fi

echo ""
echo "Continuous integration for ${appName} has been successful."