#!/usr/bin/env bash
set -e

# Pull in the upstream charts
for f in packages/*; do
	if [[ -z $CHART || $CHART == $(basename -- ${f}) ]]; then
		unset url
		if [[ -f ${f}/package.yaml ]]; then
			url=$(cat ${f}/package.yaml | yq r - url)
		fi
		if [[ -n ${url} ]]; then
			subdirectory=$(cat ${f}/package.yaml | yq r - subdirectory)
			type=$(cat ${f}/package.yaml | yq r - type)
			fields=$(echo ${subdirectory} | awk -F'/' '{print NF}')
			commit=$(cat ${f}/package.yaml | yq r - commit)
			if [[ $fields -eq '0' ]]; then
				fields='1'
			fi
			rm -rf ${f}/charts
			mkdir -p ${f}/charts
			if [[ $type == 'git' ]]; then
				mkdir -p /tmp/tmp-charts
				git clone --depth=1 --no-tags $url /tmp/tmp-charts
				pwd=$(pwd)
				cd /tmp/tmp-charts
				git fetch origin $commit
				git checkout $commit
				cd $pwd
				rm -rf ${f}/charts
				cp -r /tmp/tmp-charts/${subdirectory} ${f}/charts
				rm -rf /tmp/tmp-charts
			else
				curl -sLf ${url} | tar xvzf - -C ${f}/charts --strip ${fields} ${subdirectory} > /dev/null 2>&1
			fi
		fi
		# Loop through packages again and copy dependencies over
		# If sub-charts existed as package.yaml they will now be vendored into parent
		./scripts/prepare-subcharts ${f}

		# Apply the patch and split the CRD package
		if [[ -f ${f}/package.yaml ]]; then
			for file in $(find ./${f} -type f -name "*.patch"); do
				basename=$(basename -- ${file})
				patch -E -p3 -d ${f}/charts < ${f}/$basename
			done
			split_crds=$(cat ${f}/package.yaml | yq r - generateCRDChart.enabled)
			if [[ "${split_crds}" == "true" ]]; then
				./scripts/prepare-crds ${f}
			fi
		fi
	fi
done