#!/bin/sh

dir="$(dirname "$(readlink -f "$0")")"
root="${dir}/../"
root="$(realpath "$root")"

source "${dir}/pack.properties"

create_list() {
	find "$1" -mindepth 1 -maxdepth 1 -type d | while read -r path
	do
		realpath -s --relative-to="${root}/pack" "$path"
	done
}

create_config() {
	printf '
pack_directory = "%s"
output_file_path = "%s.zip"
'	"${root}/pack/$1" "${root}/dist/pack/$1"
	cat "${dir}/packsquash.toml"
}

package_resources() {
	printf %s\\n "$resource_list" | while read -r line
	do
		printf %s\\n "Squashing resourcepack \"$line\""
		create_config "$line" | packsquash
	done
}

package_data() {
	printf %s "$data_list" | while read -r line
	do
		zip -r "${root}/dist/pack/${line}.zip" ${root}/pack/${line}/*
	done
}

setup_index() {
	packwiz refresh
	awk -i inplace -v list="$list" -F '"' '
BEGIN {
	split(list, parts, "\n")
	for (i in parts) paths[parts[i] ".zip"]=1
}
($1 ~ /^file/) && ($2 in paths) {
	print "side = \"client\""
}
{ print }
' index.toml
}

resource_list="$(create_list "${root}/pack/config/openloader/resources/")"

# echo "$resource_list"

data_list="$(create_list "${root}/pack/config/openloader/data/")"

mkdir -p "${root}/dist"

rsync -av --delete --progress "${root}/pack" "${root}/dist" \
	$(printf " --exclude %s" $resource_list)
# 	# $(printf " --exclude %s" $data_list)

package_resources
# package_dat
cd "${root}/dist/pack" || exit
setup_index

packwiz cf export -o "${root}/dist/${TITLE}_Curseforge.zip"
packwiz mr export -o "${root}/dist/${TITLE}_Modrinth.zip"
packwiz cf export -o "${root}/dist/${TITLE}_Server.zip" -s server
cd - || exit

echo "Done!"
