#!/bin/bash


display_result() {
  dialog --title "$1" \
    --no-collapse \
    --msgbox "$result" 0 0
}

exec 3>&1
date=$(dialog --calendar "Date" 0 0 2>&1 1>&3 | awk -F "/" '{print $3"-"$2"-"$1}')
exec 3>&-

exec 3>&1
selection=$(dialog \
    --backtitle "Création d'une nouvelle évaluation: Classe" \
    --title "Menu" \
    --clear \
    --cancel-label "Exit" \
    --menu "Choisir un niveau:" 0 0 5 \
    "1" "2nd" \
    "2" "SNT" \
    "3" "Enseignements Scientifique" \
    "4" "Première NSI" \
    "5" "Première Technologique" \
    2>&1 1>&3)
exec 3>&-
case $selection in
    1 )
        tribe="2nd"
        ;;
    2 )
        tribe="SNT"
        ;;
    3 )
        tribe="Enseignement_Scientifique"
        ;;
    4 )
        tribe="1NSI"
        ;;
    5 )
        tribe="1ST"
        ;;
esac
exec 3>&1

cd $tribe
existing_seq=$(ls -d */)
nbr_seq=$(echo $existing_seq | wc -w)
next_seq_number=$(expr $nbr_seq)

title=$(dialog \
    --inputbox "Séquences trouvée\n${existing_seq/ /\n} \nNom de la nouvelle sequence (n°$next_seq_number)" \
    0 0 \
    2>&1 1>&3)
exec 3>&-
cd ..


exec 3>&1
summary=$(dialog \
    --inputbox "Résumé de la séquence" \
    0 0 \
    2>&1 1>&3)
exec 3>&-

## ajouter les tags
exec 3>&1
tags=$(dialog \
    --inputbox "Liste des tags séparés par une virgule" \
    0 0 \
    2>&1 1>&3)
exec 3>&-

## Plan de travail ou classique
exec 3>&1
selection=$(dialog \
    --backtitle "Création d'une nouvelle séquence: Type" \
    --title "Menu" \
    --clear \
    --cancel-label "Exit" \
    --menu "Type de séquence:" 0 0 4 \
    "1" "Classique" \
    "2" "Plan de travail" \
    2>&1 1>&3)
exec 3>&-
case $selection in
    1 )
        sequence_type="classique"
        ;;
    2 )
        sequence_type="plan_de_travail"
        ;;
esac


title_path=$(echo ${title// /_} | iconv -f utf8 -t ascii//TRANSLIT)
sequence_path=$tribe/$(printf "%02d" $next_seq_number)_${title_path}/
mkdir -p $sequence_path

export title=$title
export title_under=${title//?/#}
export author='Benjamin Bertrand'
export date=$date
export date_short=`date --date="$date 00:00" "+%B %Y"`
export tribe=$tribe
export tags=$tags
export summary=$summary
SKELETONPATH=./tools/skeleton/sequence
for i in `ls $SKELETONPATH/common/`
do
    envsubst < $SKELETONPATH/common/$i > $sequence_path/$i
done
for i in `ls $SKELETONPATH/$sequence_type`
do
    envsubst < $SKELETONPATH/$sequence_type/$i > $sequence_path/$i
done
