#!/bin/sh

# 直接依赖 Xcode 环境变量
productPath=${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}
cd $productPath

zconfig="{\"v\":\"$(date +%s)000\",\"packs\":{"
resources="\"resources\":{"
isFirst=1

readZCacheConfig() {
	bundlePath=$1
	isOnDemand=$2

	# 读取 packConfig 配置
	config=$(cat $bundlePath/packConfig.config)
	config=${config#\{}
	config=${config%\}||*}
	packName=${config%\{*}

	# 拼接 onDemand 配置
	if [ $isOnDemand ]; then
		config=${config%\}*}',"isOnDemand":true}'
	fi

	# 遍历子目录，找到 seq 文件夹
	seqPath=''
	for subPath in $(find $bundlePath -type d -maxdepth 1); do
		if [ "$subPath" != "$bundlePath" ] && [ "$subPath" != "$bundlePath/.DS_Store" ]; then
			seqPath=$subPath
		fi
	done
	# 检查是否找到了 seq 文件夹
	if [ -z "$seqPath" ]; then
		echo "错误：未找到 $bundlePath 下的 ZCache 资源文件"
		exit 1
	fi
	# 读取 app-res.wvc
	resConfig=$(cat $seqPath/app-res.wvc)
	resConfig=${resConfig%||*}
	# 拼接分隔符
	if [ $isFirst == 1 ]; then
		isFirst=0
	else
		zconfig="$zconfig,"
		resources="$resources,"
	fi
	# 拼接配置
	zconfig="$zconfig$config"
	resources="$resources$packName$resConfig"
}

# 扫描普通 ZCache 资源包
for bundlePath in $(find . -name "ZCache_Asset_*.bundle" -maxdepth 1); do
	readZCacheConfig $bundlePath
done

# 读取 OnDemandResources.plist
onDemandConfig=$productPath/OnDemandResources.plist
if [ -f "$onDemandConfig" ]; then
	echo "Finding On Demand Resource"
	# 这里不去具体解析 OnDemandResources.plist 的内容，一些是苹果的私有规范，可能后期更改

	onDemandResourcesPathList=(
		# 如果将 On Demand Resource 上传到苹果服务器，Build 时从 ../OnDemandResources/* 中搜索
		"$productPath/../OnDemandResources/"
		# 如果将 On Demand Resource 打包包内，那么从 ./OnDemandResources/* 中搜索
		"$productPath/OnDemandResources/"
	)
	if [ -n "$ASSET_PACK_FOLDER_PATH" ];then
		# Archive 时可以从 ASSET_PACK_FOLDER_PATH 中直接拿到路径
		onDemandResourcesPathList[2]=$ASSET_PACK_FOLDER_PATH
	fi
	for onDemandResourcesPath in "${onDemandResourcesPathList[@]}"; do
		if [ -d "$onDemandResourcesPath" ]; then
			echo "Finding On Demand Resource in $onDemandResourcesPath"
			for bundleName in $(defaults read "$productPath/OnDemandResources.plist" NSBundleResourceRequestAssetPacks); do
				if [[ $bundleName != \"ZCache_Asset_* ]]; then
					continue
				fi

				bundleName=${bundleName#\"}
				bundleName=${bundleName%\"*}
				odrResPath=$(find $onDemandResourcesPath -name "$bundleName")
				if [ -d $odrResPath ]; then
					readZCacheConfig $odrResPath true
					continue
				fi
				echo "错误：未找到 On Demand Resource $bundleName"
				exit 1
			done
		else
			echo "No On Demand Resource in $onDemandResourcesPath"
		fi
	done
fi

echo $zconfig\},$resources\}\} >ZCache_Asset.config

echo 'ZCache 静态资源配置生成完毕'
