#!/bin/bash

set -e

function get_info() {
    local field=$(echo "$fullName" | sed "$2q;d" $1);
    IFS=$3;
    local field=($field); 
    if [ "${field}" != $5 ]; then
        return 1
    fi
    local field=${field[1]};
    IFS=$4;
    local field=($field);
    local field=${field[1]};
    echo "$field"
}

function fail() {
    printf '%s\n' "$1" >&2 ## Send message to stderr.
    exit "${2-1}" ## Return a code specified by $2, or 1 by default.
}

OIFS=$IFS
NUM_LINE=2
PREFIX=""
# PREFIX=cours/algo/slides/

classes=()
for i in *.md; do
    [ -f "$i" ] || break
    date="$(get_info $i 3 ":" '"' "date")"
    if [ "$date" == 1 ]; then
        fail "Error date field not found"
    fi
    comp="$(get_info $i 2 ":" '"' "title")"
    if [ "$comp" == 1 ]; then
        fail "Error title field not found"
    fi
    i="${i%.*}"
    class="[${date}: ${comp}](${PREFIX}${i}.pdf)"
    classes+=("$class")
done
IFS=$'\n'
classes=($(sort <<<"${classes[*]}"))
date=$(date '+%Y-%m-%d')
echo "---" >> index.md
echo "title: \"Slides du cours d'algorithmique\"" >> index.md
echo "date: \"${date}\"" >> index.md
echo "---" >> index.md
echo "" >> index.md
echo "# Tous les slides du cours d'algorithmique" >> index.md
echo "" >> index.md
for i in ${classes[*]}; do
    echo "* $i" >> index.md
done


IFS=$OIFS
