#!/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

grep "//" casting*/playlist.php | sed "s|.*//[[:blank:]]*||" | sort -u | while read role
do
	printf "$role\t"
	folder=$(echo "$role" | webnormalize)
	mkdir -p "$folder"
	(
		echo "<?php"
		echo "\$customnames=array("
		grep -H "//[[:blank:]]*$role[[:blank:]]*$" casting*/playlist.php \
		| sed "s|^[[:blank:]]*\(.*\)/playlist.php:[[:blank:]]*\"| \"../\\1/|" \
		| sed "s|<span class=info>[^<]*</span>||"
		echo ");"
		echo "?>"
	) > "$folder/playlist.php"
	cat "$folder/playlist.php" | grep "=>" | wc -l
done
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" >> "$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
