#!/bin/bash

if [ $# -lt 1 ]; then
    echo "Usage:"
    echo -e "\t$(basename $0) moodle-zip-file [moodle-zip-file2] ... [out_dir]\n"
    echo "This program will extract and reorganize moodle zip files structures."
    echo "Files will be extracted in a separate folder of out_dir"
    echo "default value for out_dir is /tmp"
    exit 0
fi


function process {

    # Unzip given file to temprary working directory
    WORK_FOLDER="$2"/$(basename -s .zip "$1")
    mkdir -vp "$WORK_FOLDER"
    unzip -O Windows "$1" -d "${WORK_FOLDER}"

    # Move onlinetext to the same folder as the contribution
    # Delete onlinetext source folder (i.e. keep only one folder per student)
    find "${WORK_FOLDER}" -type d -name "*onlinetext_" | while  read d
    do
        d_dest=$(basename "${d}" | cut -d '_' -f 1-3)  # get common folder name
        echo $d_dest
        d_dest="${WORK_FOLDER}/${d_dest}_file_"  # build destination folder from common name
        mv -vi "${d}/texteenligne.html" "$d_dest"
        rmdir "${d}"
    done

    # Unzip all found compressed files (i.e. code)
    find "${WORK_FOLDER}" -type f -regex ".*\.\(tar.gz\|tgz\|tar\|tar.xz\|bz2\|rar\|zip\|\)" | while read f
    do
        echo " ========= Attempt to extract ${f} ========="
        dest=$(dirname "${f}")
        case "${f}" in
            *.tar.gz|*.tgz)    tar -xvzf "${f}" -C "${dest}" && rm -v "${f}" ;;
            *.tar|*.tar.xz)    tar -xvf "${f}" -C "${dest}" && rm -v "${f}"  ;;
            *.bz2)    echo "Format bunzip not implemented yet" ;;
            *.rar)    echo "Format RAR not implemented yet" ;;
            *.zip)    unzip "${f}" -d "${dest}" && rm -v "${f}" ;;
            *)        echo "'${f}' cannot be extracted" ;;
        esac
    done


    read -p " (!!! NOT working yet) Do you want to delete all ELF files in the extracted folders ? (yes/no) " yn
    case ${yn} in
        yes|y)      $(find "${WORK_FOLDER}" -type f -print0 | grep ELF | cut -d':' -f1)  ;;
        *)          echo "Skipping ELF suppression..."  ;;
    esac
}

# Get last argument, if does not exist -> folder to be created
last=${@:$#}
if [ ! -e "${last}" ]; then
    mkdir -pv "${last}"
fi

# If last argument is a folder -> this is out_dir otherwise use default out_dir
if [ -d "${last}" ]; then
    OUT_DIR="$last"
    FILES=${@:1:$#-1}
else
    OUT_DIR="/tmp"
    FILES=${@}
fi

for f in ${FILES}; do
    process "${f}" "${OUT_DIR}"
done
