#!/bin/sh

#[ "$1" ] || exit 1
#[ -f "$1" ] || exit 2

PGM=`basename "$0"`
PATH="$PATH:"$(dirname "$0")
TMP="/tmp/$PGM"

ls casting*/playlist.php 2>/dev/null || exit 1

base=$(pwd)
ls casting*/.sources/liste 2>/dev/null || while read liste
do
	cd $base/$(dirname "$liste") || exit 3
	makeplaylist "$list" | sed "s/\$reserve=/\$customnames=/" > ../playlist.php || exit 4
done

castings=$(ls -d casting* | sed -E "s/^([a-z]+)([0-9]+)/\\2\t\\1\\2/" | sort -n | cut -f 2-)

# grep -h // casting*/.sources/liste \
# | sed -e "s:.*// *::" -e "s/ *, */\n/g" \
# | sort -u | while read label; do
# 	tag=$(webnormalize "$label")
# 	mkdir -p _$tag
# 	echo "$label" > _$tag/_pagetitle.txt
# 	printf "%s\t%s\n" "$tag" "$label"
# done > $TMP.roles

grep "//" casting*/playlist.php | sed "s|.*, *//[[:blank:]]*||" | while read roles
do
	echo "$roles" | sed -E "s#[[:blank:]]*(//*|,)[[:blank:]]*#\n#g" | grep .
done | sort -u | while read role
do
	printf "$role\t"
	folder=$(echo "$role" | webnormalize)
	egrep -H "(/|,)[[:blank:]]*$role[[:blank:]]*(,|/|$)" casting*/playlist.php \
	| sed "s|^[[:blank:]]*\(.*\)/playlist.php:[[:blank:]]*\"| \"../\\1/|" \
	| sed "s|<span class=info>[^<]*</span>||" > $TMP.unsorted

	for casting in $castings
	do
		grep "$casting/" $TMP.unsorted
	done >$TMP.items

	mkdir -p "$folder"
	(
	echo "<?php"
	echo "\$customnames=array("
	cat $TMP.items
	echo ");"
	echo "?>"
	) > "$folder/playlist.php"
	cat "$folder/playlist.php" | grep "=>" | wc -l
done
[ -d "toc" ] && castingtoc > toc/_about.html && echo "TOC updated"
echo

# casting="$1"
# cat "$casting" | grep "_(" | cut -d "(" -f 2 | cut -d ")" -f 1 | sort -u | while read role
# do
# 	mkdir -p "$role"
# 	echo "<?php" > "$TMP.$role"
# 	echo "\$customnames=array(" >> "$TMP.$role"
# 	touch "$TMP.$role"
# 	grep "($role)" "$casting" | while read line
# 	do
# 		name=`echo "$line" | cut -d "\"" -f 2 | sed "s/_(.*//" | sed "s/.*\///"`
# 		egrep "[0-9]-$name" "$TMP.$role" >/dev/null
# 		if [ ! $? -eq 0 ]
# 			then
# 			egrep "[0-9]-$name" "$casting / Piscine" >> "$TMP.$role"
# 		fi
# 		printf "\t$line\n" >> "$TMP.$role"
# 	done
# 	printf ");\n" >> "$TMP.$role"
# 	printf "?>" >> "$TMP.$role"
# 	cat "$TMP.$role" >> "$role/playlist.php"
# 	echo
# done
