#!/bin/bash

################################################################################
# importe les fichiers org modifiés pour une publication
# 
# Copyright (C) 2022 rick G. <rick@gnous.eu>
# 
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
# 
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License along with
# this program. If not, see <https://www.gnu.org/licenses/>.
################################################################################

# couleurs
red="\e[31m"
blue="\e[34m"
green="\e[32m"
reset="\e[0m"

origin="$HOME/Documents/partages/"
folders="moocs confs"
dest="nec/"

################################################################################
# Vérifie si un fichier distant existe déjà ou pas. L'importe s'il est nouveau
# ou s'il a été modifié; ne fait rien sinon.
#
# Globals:
#     $origin: le chemin où se trouve les fichiers
#     $dest: le dossier local où seront importés les fichiers
#     $red/$blue/$green/$reset: les couleurs
# Arguments:
#     $1: le chemin du fichier à vérifier / importer
#         ex: /home/X/Documents/partages/confs/fichier.org 
################################################################################
check ()
{
    tmp=${1/$origin/$dest} # nouveau chemin
    filename=${1/$origin/} # on garde le chemin dans le dossier d'origine
    pathfile=$(dirname $filename) # chemin sans le nom du fichier

    diff -q $1 $tmp 1> /dev/null 2>&1
    case $? in
        1) echo -e "[$blue C $reset] Copie de $1 vers $tmp."
            cp $1 $tmp
            ;;
        2) echo -e "[$green A $reset] Nouveau fichier: $filename"
            mkdir -p $dest$pathfile # on créé le dossier s'il n'existe pas
            cp $1 $tmp
            ;;
        *) echo -e "[$red R $reset] $filename non modifié."
            ;;
    esac
}

if [ ! -d $dest ]
then
    echo "Create $dest..."
    mkdir $dest
fi

for i in ${folders}
do
    for j in $(find "$origin$i" -type f -iname "*.org")
    do
        check $j
    done
done