#!/bin/bash
# divise un texte $1 (sous la forme fichier.txt) en chapitres (ou sections) dans un dossier selon un critère $2. Si $3=test, la découpe ne se fait pas.
txt=$1
criterium=$2
chemin=$3
test=$4

if [ "$test" = "" ]
then
	echo "\$1 : texte ; \$2 : critère ; \$3 : chemin où créer les découpes ; \$4 : test ou non"
	exit
fi

if [ "$txt" = "test" ]
then
	txt=""
	test=test
fi
	

if [ "$txt" = "" ]
then
	txt=biophar.txt
fi

if [ "$criterium" = "" ]
then
	criterium=SECTION
fi

pwd=$PWD
folder=$pwd/$(echo $txt | sed -e "s/\....$//g")
echo "folder to create : " $folder


if [ -d $folder ]
then
	echo "$folder to erase !"
	if [ "$test" != "test" ]
	then
		mv $folder $folder.$(date +%F.%H.%M.%S)
	fi
fi

if [ "$test" != "test" ]
then
	mkdir $folder
	cd $folder
	txt=../$txt
else
	echo TEST MODE
fi


num=0
file=00.$(echo $criterium | sed -e "s/ /_/g" -e "s/$criterium//g" | erg-minuscules)

# log
# echo txt=$txt
# echo criterium=$criterium
# echo test=$test
# echo file=$file
# echo folder=$folder

cat $txt | while read l
do
	section=$(echo "$l" | grep "$criterium" )
	if [ -n "$section" ]
	then
		# s'il s'agit d'un indicateur de section
		num=$[ num + 1 ]
		# si le numéro de fichier est inférieur à dix, on écrira 01, 02, etc.
		if [ "$num" -lt "10" ]
		then
			file=../$chemin/0$num$(echo "$l" | sed -e "s/  / /g" -e "s/ /_/g" -e "s/$criterium//g" | erg-minuscules)
		else
			file=../$chemin/$num$(echo "$l" | sed -e "s/  / /g"  -e "s/ /_/g" -e "s/$criterium//g"  | erg-minuscules)
		fi
		echo "$file"
	elif [ "$test" != "test" ]
	then
		echo $l >> $file
	fi
done

if [ "$test" != "test" ]
then
	cd ..
fi
