#!/bin/sh -e

DIST_DIR=dist
SRC_DIR=src

generate_index() {
	printf '// DO NOT EDIT! Generated with "npm run build".\n\n'
	for dir in $(find "$SRC_DIR/$1" -type d); do
		for file in "$dir/"*.scss; do
			case $file in "$dir/*.scss"|*/index.scss)
				break
			esac

			file=${file#"$SRC_DIR/$1/"}
			file=${file%.scss}
			mod=$(printf '%s' "$file" | tr '[:punct:]' '-')
			printf '@use "%s" as %s;\n' "$file" "$mod"
		done
		printf '\n'
	done
}

# Special behavior because steam-theming-utils requires the file names of each
# named React component to be available, and IDK how to do that with @use
if [ "$1" = steam ]; then
	dir=$DIST_DIR/$1

	# Remove if file already exists for the "release" script
	[ -f "$file" ] && rm "$file"
	# .5s shaven off
	bunx postcss "$SRC_DIR/$1/index_shared.scss" --output "$dir.css"
	bunx postcss "$SRC_DIR/$1/client/**/*.scss" \
		--base "$SRC_DIR" \
		--dir "$DIST_DIR" \
		--ext css
	find "$dir" -type f | xargs cat >> "$dir.css"
	rm -rf "$dir"
	exit
fi

mkdir -p "$DIST_DIR"
# Firefox has its separate index file for the browser UI and web content already
if [ "$1" = firefox ]; then
	bunx postcss "$SRC_DIR/firefox/index_$2.scss" \
		--output "$DIST_DIR/firefox_$2.css"
else
	index=$SRC_DIR/$1/index.scss

	generate_index "$1" > "$index"
	bunx prettier -w "$index" > /dev/null
	bunx postcss "$index" --output "$DIST_DIR/$1.css"
fi
