#! /usr/bin/bash

set -Eeuo pipefail

################################################################################
# get script file location
################################################################################

SCRIPT_PATH="$(realpath -e ${BASH_SOURCE[0]})";
SCRIPT_DIR="${SCRIPT_PATH%/*}"

################################################################################
# Whispercpp variables
################################################################################

#MODEL_PATH="${MODEL_PATH:-${SCRIPT_DIR}/whisper.cpp/models/ggml-tiny.en-q5_0.bin}"
MODEL_PATH="${MODEL_PATH:-/home/dax/git/whisper.cpp/models/ggml-large-v2.bin}"
#WHISPER_EXECUTABLE="${WHISPER_EXECUTABLE:-${SCRIPT_DIR}/whisper.cpp/main}";
WHISPER_EXECUTABLE="${WHISPER_EXECUTABLE:-/home/dax/git/whisper.cpp/main}"
WHISPER_LANG="${WHISPER_LANG:-en}";
WHISPER_THREAD_COUNT="${WHISPER_THREAD_COUNT:-4}";

################################################################################
#
################################################################################

msg() {
    echo >&2 -e "${1-}"
}

cleanup() {
    local -r clean_me="${1}";

    if [ -d "${clean_me}" ]; then
      msg "Cleaning up...";
      rm -rf "${clean_me}";
    else
      msg "'${clean_me}' does not appear to be a directory!";
      exit 1;
    fi;
}

print_help() {
    echo "################################################################################"
    echo "# Usage: ./dt_transctibe_mp3_to_text.sh <path_to_mp3>"
    echo "# Requirements: ffmpeg pandoc whisper.cpp"
    echo "################################################################################"
}

check_requirements() {
    if ! command -v ffmpeg &>/dev/null; then
        echo "ffmpeg is required";
        exit 1
    fi;

    if ! command -v pandoc &>/dev/null; then
        echo "pandoc is required";
        exit 1;
    fi;

    if ! command -v libreoffice &>/dev/null; then
        echo "libreoffice is required";
        exit 1;
    fi;

    if ! command -v "${WHISPER_EXECUTABLE}" &>/dev/null; then
        echo "The C++ implementation of Whisper is required: https://github.com/ggerganov/whisper.cpp"
        exit 1;
    fi;

}

if [[ "${#}" -lt 1 ]]; then
    print_help;
    exit 1;
fi

if [[ "${1##-*}" == "help" ]]; then
    print_help;
    exit 0;
fi

check_requirements;

################################################################################
# create a temporary directory to work in
# set the temp_dir and temp_filename variables
################################################################################

temp_dir="$(mktemp -d ${SCRIPT_DIR}/temp/tmp.XXXXXX)";
cd "${temp_dir}";

################################################################################
# Resamping
################################################################################

source_audio="${1}"

title_name=$(echo "${source_audio}" | xargs basename -s '.mp3');

msg "Resampling audio...";

ffmpeg -i "${source_audio}"  \
    -hide_banner \
    -vn \
    -loglevel error \
    -ar 16000 \
    -ac 1 \
    -c:a pcm_s16le \
    -y \
    "${temp_dir}/${title_name}.wav";

################################################################################
# Transcribing
################################################################################

msg "Transcribing...";
msg "Whisper specified at: '${WHISPER_EXECUTABLE}'";

"${WHISPER_EXECUTABLE}" \
    -m "${MODEL_PATH}" \
    -l "${WHISPER_LANG}" \
    -f "${temp_dir}/${title_name}.wav" \
    -t "${WHISPER_THREAD_COUNT}" \
    -of "${temp_dir}/${title_name}" \
    -pp \
    -nt \
    -otxt;


transcript_raw="${transcript_raw:-${temp_dir}/${title_name}.txt}";

meta_title=$(ffprobe -loglevel error -show_entries format_tags=title -of default=noprint_wrappers=1:nokey=1 "${source_audio}")

date_string=$(echo "${meta_title}" | cut -c 1-6)
title_string=$(echo "${meta_title}" | cut -d " " -f 2-)

yaml_date=$(date --date="${date_string}" "+%B %e, %Y")
yaml_title="${title_string}"
year_string=$(date --date="${date_string}" "+%Y")

sed -i -e '1i\' -e "---" "${transcript_raw}";
sed -i -e '2i\' -e "title: ${yaml_title}" "${transcript_raw}";
sed -i -e '3i\' -e "author: Ṭhānissaro Bhikkhu" "${transcript_raw}";
sed -i -e '4i\' -e "date: ${yaml_date}" "${transcript_raw}";
sed -i -e '5i\' -e "url: <https://www.dhammatalks.org/Archive/y${year_string}/${title_name}.mp3>" "${transcript_raw}";
sed -i -e '6i\' -e "---" "${transcript_raw}";
sed -i -e '7i\' -e "" "${transcript_raw}";

mv "${temp_dir}/${title_name}.txt" "${temp_dir}/${title_name}.md";

pandoc -f markdown -t odt --data-dir="${SCRIPT_DIR}/pandoc_data" --reference-doc "${SCRIPT_DIR}/pandoc_data/custom-reference.odt" --template="${SCRIPT_DIR}/pandoc_data/custom-template.txt" "${temp_dir}/${title_name}.md" -o "${temp_dir}/${title_name}.odt";

libreoffice --convert-to docx "${temp_dir}/${title_name}.odt";

################################################################################
# moving and clean up
################################################################################

cd "${SCRIPT_DIR}";
# cp "${source_audio}" ../audio;
sed -i "$ a\
https://www.dhammatalks.org/Archive/MachineTranscripts/docx/${title_name}.docx" ../drafts/drafts_url_lists.txt;
mv "${source_audio}" ../audio/finished;
mv "${temp_dir}/${title_name}.md" ../drafts/md;
# mv "${temp_dir}/${title_name}.odt" ../drafts/odt;
mv "${temp_dir}/${title_name}.docx" ../drafts/docx;

cleanup "${temp_dir}";

msg "Done! The draft transcription ${title_name} is ready to edit.";

