#!/usr/bin/env bash


# Exit on error
set -e


#determine ios folder
if [[ -d ./_ios ]]; then
	IOS_DIR=./_ios

	if [[ -d ./ios ]]; then
		TVOS_DIR=./ios
	else
		echo "Error: could not find './ios' folder with tvos content"
		exit 1
	fi	
elif [[ -d ./ios ]]; then
	IOS_DIR=./ios

	if [[ -d ./tvos ]]; then
		TVOS_DIR=./tvos
	else
		echo "Error: could not find './tvos' folder with tvos content"
		exit 1
	fi	
else
	echo "Error: could not find './ios' or './_ios' folder"
	exit 1
fi	


IOS_FLUTTER_ASSETS_DIR=$IOS_DIR/Flutter/App.framework/flutter_assets
TVOS_FLUTTER_ASSETS_DIR=$TVOS_DIR/tvos_flutter_assets/flutter_assets


if [[ -d $IOS_FLUTTER_ASSETS_DIR ]]; then

	echo "Copying flutter_assets from IOS compiled target"


	# better approuch would to copy complete assets folder and remove files that are generated by compilation step
	# isolate_snapshot_data, isolate_snapshot_instr, kernel_blob, vm_snapshot_data
	# note, this list might be different for debug (jit) and release (aot)??????
	
	rm -rf "$TVOS_FLUTTER_ASSETS_DIR"
	mkdir -p "$TVOS_FLUTTER_ASSETS_DIR"

	echo " └─App.framework/flutter_assets/AssetManifest.json"
	cp -v "$IOS_FLUTTER_ASSETS_DIR/AssetManifest.json" "$TVOS_FLUTTER_ASSETS_DIR/AssetManifest.json"

	echo " └─App.framework/flutter_assets/FontManifest.json"
	cp -v "$IOS_FLUTTER_ASSETS_DIR/FontManifest.json" "$TVOS_FLUTTER_ASSETS_DIR/FontManifest.json"

set +e
	# the content has changed from flutter v 1.15.19 to 1.19.0-4.3pre
	echo " └─App.framework/flutter_assets/LICENSE"
	cp -v "$IOS_FLUTTER_ASSETS_DIR/LICENSE" "$TVOS_FLUTTER_ASSETS_DIR/LICENSE"

	echo " └─App.framework/flutter_assets/NOTICES"
	cp -v "$IOS_FLUTTER_ASSETS_DIR/NOTICES" "$TVOS_FLUTTER_ASSETS_DIR/NOTICES"

	echo " └─App.framework/flutter_assets/assets/"
	mkdir -p "$TVOS_FLUTTER_ASSETS_DIR/assets"
	cp -v -R "$IOS_FLUTTER_ASSETS_DIR/assets" "$TVOS_FLUTTER_ASSETS_DIR"

	echo " └─App.framework/flutter_assets/fonts/"
	mkdir -p "$TVOS_FLUTTER_ASSETS_DIR/fonts"
	cp -v -R "$IOS_FLUTTER_ASSETS_DIR/fonts" "$TVOS_FLUTTER_ASSETS_DIR"

	echo " └─App.framework/flutter_assets/packages/"
	mkdir -p "$TVOS_FLUTTER_ASSETS_DIR/packages"
	cp -v -R "$IOS_FLUTTER_ASSETS_DIR/packages" "$TVOS_FLUTTER_ASSETS_DIR"

set -e
	echo " └─Done"
 	
else
    echo "'./ios/Flutter/App.framework/flutter_assets' folder does not not exist or IOS target not compiled yet, build any ios buiild first!"
    exit 1
fi