#! /bin/bash
Version="12-dec-2023-0 Last Update : `stat -c %z $0 | cut -d"." -f1`"

PasswordOption=""
ModelOption=""
Fields="1 2"
ColNom="2"
ColPrenom="3"
case "$1" in
-h|--help)
	echo "Version : $Version"
	echo "Services affectes aux groupes, td integre au prefixe"
	echo "Syntax"
	echo ""
	echo "print this help"
	echo "$0 [-h|--help]"
	echo ""
	echo "generate a creation script"
	echo "$0 [-m|--model model_name] [-p|--password db_admin_passwords_file] instruction_file"
	echo ""
	echo "print a creation sequence"
	echo "$0 [-m|--model model_name] [-p|--password db_admin_passwords_file] service_name : list_of_csv_files : list_of_td_numbers"
	echo ""
	echo "format of instruction_file"
	echo "service_name : list_of_csv_files : list_of_td_numbers"
	echo ""
	echo "with --password option, every database gets a new password for its admin user"
	echo "and a file of passwords is generated with following syntax:"
	echo "service	database	admin	password"
	echo ""
	echo "set a model"
	echo "$0 -s|--set_model model_name model_instructions_to choose_the_archive"
	echo "last set model is a default model"
	echo ""
	echo "select colomns of csv files"
	echo ""
	echo "$0 -c|--csv list_of fields"
	echo "Elements of list of fields are N, N-M, N-, -N, see man cut for more"
	echo "Default is 1 2"
	echo ""
	echo "get last version of this scipt"
	echo "$0 -u|--update"
	echo ""
	echo "example:"
	echo "$0 --set_model matski /home/sisalpuser/xoe.packages/database_models.matski/11.0/reference_matski_td\$Td.sql.gz"
	echo "$0 --csv 3 2"
	echo "echo \"srv1 : gra.csv grb.csv : 1 2\" > instructions.txt"
	echo "$0 --model matski --password password_list.txt instructions.txt"
	exit 0
	;;
-s|--set_model)
	ModelName="$2"
	echo "ArchivePath=\"$3\"" > $ModelName.conf
	chmod 755 $ModelName.conf
	echo "$ModelName"  > model.conf
	exit 0
	;;
-c|--csv)
	shift
	Fields="$*"
	echo "Fields=\"$Fields\"" > fields.conf
	chmod 755 fields.conf
	exit 0
	;;
-u|--update)
	mv $0 $0.old
	if wget http://download.sisalp.net/scripts/db_setup_script.sh ; then
		chmod 755 db_setup_script.sh
		diff $0.old $0
		rm $0.old
		exit 0
	else
		mv $0.old $0
		echo "Failed to download a new version of $0"
		exit 1
	fi
	;;
esac
case "$1" in
-m|--model)
	ModelName="$2"
	ModelOption="--model $ModelName"
	shift
	shift
	;;
esac
case "$1" in
-p|--password)
	PasswordFile="$2"
	PasswordOption="--password $PasswordFile"
	shift
	shift
	;;
esac
case "$1" in
-m|--model)
	ModelName="$2"
	shift
	shift
	;;
esac
if [ -z "$ModelName" ] ; then
	if [ -f model.conf ] ; then
		ModelName=`cat model.conf`
		ModelOption="--model $ModelName"
	fi
fi

#-------------------------------------------------------------------------
NEW_PASSWORD ()
#-------------------------------------------------------------------------
{
				if [ -z "$1" ] ; then
					pw_nb_digits="7 3 5"
				else
					pw_nb_digits="$*"
				fi
				pw_letters=(a b c d e f g h i j k m n o p q r s t u v w x y z A B C D E F G H I J K L M N P Q R S T U V W X Y Z 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 )
				pw_range="${#pw_letters[*]}"
				NEW_PWD=""
				for nb_digit in $pw_nb_digits ; do
					#strings /dev/urandom | grep -o '[0-9A-Za-z]' | head -n 100 | tr -d '\n'; echo
					if [ ! -z "$NEW_PWD" ] ; then NEW_PWD="${NEW_PWD}""_" ; fi
					for ((  pw_digit = 1 ;  pw_digit <= $nb_digit ;  pw_digit++  )) ; do
						pw_index="$(($RANDOM%$pw_range))"
						NEW_PWD="${NEW_PWD}""${pw_letters[$pw_index]}"
					done
				done
				echo "$NEW_PWD"
}
#-------------------------------------------------------------------------
standard_IFS="$IFS" ;
line_IFS=$'\n' ;
FOR_LINE () { IFS="$line_IFS" ; }
DO () { IFS="$standard_IFS" ; }
DONE_LINE () { IFS="$line_IFS" ; }
DONE () { IFS="$standard_IFS" ; }
#example
#FOR_LINE ; for line in `cat $file` ; do DO
#	....
#DONE_LINE ; done ; DONE

if [ -z "$1" ] ; then
	$0 --help
	exit 0
fi

if [ -z "$2" ] ; then
	Instructions_file="$1"
	if [ ! -f $Instructions_file ] ; then
		echo "Instructions_file $Instructions_file is not found"
		exit 1
	fi
	CreatorScript="db_creator-$$.sh"
	echo "#! /bin/bash"	> $CreatorScript
	echo "# `date` $0 $*"	>> $CreatorScript
	Instructions=`cat $Instructions_file | grep -v "^#"`
	FOR_LINE ; for instruction in $Instructions ; do DO
		Service=`echo "$instruction" | cut -d: -f2 | xargs`
		ListFiles=`echo "$instruction" | cut -d: -f1 | xargs`
		Tds=`echo "$instruction" | cut -d: -f3 | xargs`
		$0 $ModelOption $PasswordOption $instruction >> $CreatorScript
	DONE_LINE ; done ; DONE
	echo "exit 0" >> $CreatorScript
	chmod 755 $CreatorScript
	echo ""
	echo "Execute $CreatorScript to create databases"
	exit 0
fi
instruction="$*"
case "$instruction" in
*:*:*)
	Service=`echo "$instruction" | cut -d: -f1 | xargs`
	ListFiles=`echo "$instruction" | cut -d: -f2 | xargs`
	Tds=`echo "$instruction" | cut -d: -f3 | xargs`
	;;
*)
	$0 --help
	exit 0
	;;
esac
echo "# install td $Tds for $ListFiles on service $Service"
echo "# ---------------------------------------------------"
if [ -f fields.conf ] ; then
	. ./fields.conf
fi
for GroupeFile in $ListFiles ; do
	Groupe=`basename $GroupeFile .csv`
	if [ -f /usr/bin/uni2ascii ] ; then
		Etudiants=`cat $GroupeFile | uni2ascii -Bq | sed s/";"/","/g | grep -v "^Nom," | grep -v "^,"`
		#echo "uni2ascii $Etudiants"
	else
		Etudiants=`cat $GroupeFile | iconv -f utf-8 -t US-ASCII//TRANSLIT | sed s/";"/","/g | grep -v "^Nom," | grep -v "^,"`
		#echo "iconv $Etudiants"
	fi
	separator=""
	for Td in $Tds ; do
		separator=""
		FOR_LINE ; for Ligne in $Etudiants ; do DO
			Etudiant=""
			for field in $Fields ; do
				partofname=`echo "$Ligne" | cut -d, -f$field`
				Etudiant="${Etudiant}_$partofname"
			done
			Etudiant=`echo "${Etudiant}" | tr '[:upper:]' '[:lower:]' | tr '[:punct:]' '_' | tr ' ' '_' | sed s/__/_/g | sed s/_$// | sed s/^_//`
			db_created=`echo "${Groupe}_td${Td}_${Etudiant}" | tr '[:upper:]' '[:lower:]' | tr '[:punct:]' '_' | tr ' ' '_' | sed s/__/_/g`

			if [ -f $ModelName.conf ] ; then
				. ./$ModelName.conf
				echo "echo \"create database ${db_created} on service $Service from $ArchivePath\""
				if [ -f  $ArchivePath ] ; then
					echo "xoe --database -restore -force $Service ${db_created} $ArchivePath ;"
					case "$PasswordOption" in
					--password*)
						if [ ! -f $PasswordFile ] || ! cat $PasswordFile | grep -q "$Etudiant" ; then
							echo "# New password for student $Etudiant"
							adminpassword="admin_`NEW_PASSWORD 3 3`"
							echo "$Service	${Etudiant}	admin	$adminpassword" >> $PasswordFile
						else
							adminpassword=`cat $PasswordFile | grep "$Etudiant" | cut -f4`
						fi
						echo "xoe --database -admin_password $Service ${db_created} $adminpassword ;"
						;;
					esac
				else
					echo "# archive file $ArchivePath is not found"
				fi
			else
					echo "# model configuration $ModelName.conf is not found"
			fi	

			echo "sleep 2 ; "
		DONE_LINE ; done ; DONE
		echo "# ---------------------------------------------------"
	done
	#Service=$[$Service +1]
done
exit 0
