#!/usr/bin/env bash

error() {
    printf -v message "\e[31mERROR:\e[0m %s\n" "$1"
    message="${message}  \e[1mStack trace\e[0m:\n"
    for ((i = 1; i < ${#FUNCNAME[@]}; i++)); do
        if [[ $i = $((${#FUNCNAME[@]} - 1)) ]]; then
            message="${message}  └"
        else
            message="${message}  ├"
        fi
        message="${message}─ source:\e[3;34m${BASH_SOURCE[$i]}\e[0m"
        message="${message} function:\e[3;34m${FUNCNAME[$i]}\e[0m"
        message="${message} line:\e[3;34m${BASH_LINENO[$i - 1]}\e[0m\n"
    done
    >&2 printf "%b\n" "${message}"
}

die() {
    error "$*"
    exit 1
}
# shellcheck disable=SC2317
process_args() {
    while :; do
        case $1 in
        -l | --label)
            key_label="$2"
            shift
            ;;
        -r | --recorder)
            recorder_label="$2"
            shift
            ;;
        *)
            conf="$*"
            break
            ;;
        esac
        shift
    done
}

mount_device() {
    if [[ $# -lt 1 || $# -gt 2 ]]; then
        error "mount_device need 1 or 2 arguments, $# provided : '$*'"
        return 1
    fi
    local label="$1"
    local unmount="${2:-0}"
    local device
    if [[ $unmount -eq 1 ]]; then
        printf "Unm"
    else
        printf "M"
    fi
    printf "ount device with Label %s\n" "$label"
    device="/dev/$(lsblk -o KNAME,LABEL | grep "${label}" | awk '{print $1}')"

    # check is we found a device with this name
    if [[ $device = "/dev/" ]]; then
        error "Can't get device named $label is device plugged?"
        return 1
    fi
    local command
    if [[ $unmount -eq 1 ]]; then
        command="unmount"
    else
        command="mount"
    fi

    if ! udisksctl "${command}" -b "${device}"; then
        error " -> Error mounting device $device for $label"
        return 1
    fi
    sleep 1
    return 0
}

get_file_hash() {
    if [[ ! $# -eq 2 ]]; then
        error "get_file_size need 2 arguments, $# provided : '$*'"
        return 1
    fi
    local file
    local file_size

    file=$1
    file_size=${2:-1}
    if ((file_size != -1)); then
        if [[ -f "$file" ]]; then
            if ((file_size > 0)); then
                if ((file_size > 2000000)); then
                    #calculate
                    local tmp_file
                    tmp_file=mktemp
                    head -c 1MB "$file" >"$tmp_file"
                    tail -c 1MB "$file" >>"$tmp_file"
                    printf "%s" "$(md5sum "$tmp_file" | cut -d" " -f 1)"
                    rm "$tmp_file"
                else
                    printf "%s" "$(md5sum "$file" | cut -d" " -f 1)"
                fi
                return
            fi
        fi
    fi
    printf "%s" -1
}

move_file() {
    if [[ ! $# -eq 2 ]]; then
        error "move_file need 2 arguments, $# provided : '$*'"
        return 1
    fi
    local source="$1"
    local destination="$2"

    printf "Move %s to  %s\n" "$source" "$destination"
    if [[ ! -d "${destination%/*}" ]]; then
        error "$destination directory does not exists"
        return 1
    fi

    if ! mv "$source" "$destination"; then
        error "Error moving $source file, file seems to not exists"
        return 1
    fi
    return 0
}

get_file_size() {
    if [[ ! $# -eq 1 ]]; then
        error "get_file_size need 2 arguments, $# provided : '$*'"
        return 1
    fi
    local file
    file=$1
    if [[ -f "$file" ]]; then
        wc -c <"$file"
        return
    fi
    printf "%s" -1
}

insert_media() {
    if [[ ! $# -eq 2 ]]; then
        error "insert_media need 2 arguments, $# provided : '$*'"
        return 1
    fi
    local filename filesize filehash tag
    filename="$1"
    tag="$2"
    if [[ ! -f "$filename" ]]; then
        error "File $filename not found, can't insert media"
        return 1
    fi
    if [[ -z "$tag" ]]; then
        error "Tag not defined, can't insert media (filename: $filename)"
        return 1
    fi
    filesize=$(get_file_size "$filename")
    filehash=$(get_file_hash "$filename" "$filesize")
    if ! sed -i \
        -e "s#\[\[${tag}\]\]#${filename}#g" \
        -e "s#\[\[${tag}_filesize\]\]#${filesize}#g" \
        -e "s#\[\[${tag}_filehash\]\]#${filehash}#g" \
        "${folder}/montage.kdenlive"; then
        error "sed command error on insert media!"
        return 1
    fi
    return 0
}

function main() {
    process_args "$@"

    base_dir="${HOME}/medias/videos/sambab"
    key_label=${key_label:-"SAMBAB"}
    recorder_label=${recorder_label:-"LS-100"}

    printf "Creation de la conférence de %s\n" "$conf"
    cd ~/medias/videos/sambab || exit 1

    #Get las friday date for creating folder
    friday=$(date --date='last Friday' +"%Y.%m.%d")

    #Add basedir, then I have my directory
    folder="${base_dir}/${friday}-${conf// /_}"

    # create it
    mkdir "${folder}/"{rushes,audio,titles} -p || die "folder creation failed"

    cp "${base_dir}/logo_amis.svg" "${folder}/titles" || die "SVG copy failed!"
    cp "${base_dir}/template.kdenlive" "${folder}/montage.kdenlive" || die "Template copy failed!"

    inkscape_date=$(LC_ALL=fr_FR.UTF-8 date --date='last Friday' +"%A %d %B %Y")

    printf "Put Name on title\n"
    sed -i "s/\[\[conf\]\]/${conf//_/ }/g" "${folder}/titles/logo_amis.svg" || die "Change text on credits screen failed!"

    printf "Put date on title\n"
    sed -i "s/\[\[date\]\]/${inkscape_date}/g" "${folder}/titles/logo_amis.svg" || die "Change date failed!"

    printf "Export SVG title \n"
    inkscape --export-type="png" "${folder}/titles/logo_amis.svg" || die "SVG export failed"

    printf "Importing PNG File in %s/montage.kdenlive \n" "$folder"
    insert_media "$folder/titles/logo_amis.png" "logo"

    ## Get file from USB key
    if mount_device "$key_label"; then
        move_file "/run/media/${USER}/${key_label}/RECORD/EXREC/"*.MP3 "${folder}/audio/audio.mp3"
        move_file "/run/media/${USER}/${key_label}/$(date --date='last Friday' +'%Y-%m-%d')"\ *.mkv "${folder}/rushes/obs.mkv"
        mount_device "$key_label" 1
    fi

    ## Get audio file from RECORDER
    if mount_device "$recorder_label"; then
        move_file "/run/media/${USER}/${recorder_label}/RECORDER/FOLDER_A/"VOC_*.wav "${folder}/audio/recorder.wav"
    fi

    move_file "$HOME/downloads/$(date --date='last Friday' +'%Y%m%d')"_*.mp4 "${folder}/rushes/presensation.mp4"

    insert_media "${folder}/audio/audio.mp3" audio
    insert_media "${folder}/rushes/obs.mkv" video
    insert_media "${folder}/audio/recorder.wav" audio_recorder
    insert_media "${folder}/rushes/presensation.mp4" video_intro

    printf "Change root folder in montage.kdenlive to %s\n" "$folder"
    sed -i -e "s#\[\[root_folder\]\]#${folder}#g" "${folder}/montage.kdenlive"
}

main "$@"
exit 0
