#!/usr/bin/env bash

if [ "$#" -lt 2 ]; then
  echo "Usage: ytconv [options] [<image>] <audio 1> [<audio 2> [... <audio N>]]"
  printf '%b\n' "\nOptions:"
  printf '%b\n' "\t-t\t\tproduce only out.txt"
  exit 1
fi

if [ "$1" != "-t" ]; then
  identify "$1" >/dev/null 2>&1 || {
    echo "ERROR: \`$1' is not an image file."
    exit 1
  }

  tmpdir=$(mktemp -d /tmp/tmp.ytconv.$$.XXXXXX)
  tmpimg=${tmpdir}/image.png
  tmpalist=${tmpdir}/audio_list

  echo "Converting image..."
  img="$1"
  shift 1 # remove image from args
  convert "${img}" "${tmpimg}"
  mogrify -resize 1920x1080 "${tmpimg}"
  # ffmpeg does not accept images with odd width or height
  imgwidth=$(identify -format '%w' "${tmpimg}")
  imgheight=$(identify -format '%h' "${tmpimg}")
  if [ $((imgwidth % 2)) -ne 0 ]; then
    imgwidth=$((imgwidth - 1))
    mogrify -crop "${imgwidth}x${imgheight}+0+0" "${tmpimg}"
  fi
  if [ $((imgheight % 2)) -ne 0 ]; then
    imgheight=$((imgheight - 1))
    mogrify -crop "${imgwidth}x${imgheight}+0+0" "${tmpimg}"
  fi

  for x in "$@"; do
    file_path=$(readlink -f "${x}")
    # because ffmpeg doesn't have a way to escape all special characters we
    # create symbolic link of the file that contains only alfanumeric characters
    ln_file=$(mktemp "${tmpdir}"/XXXXXX)
    ln_file="${ln_file}.${x##*.}"
    ln -fs "${file_path}" "${ln_file}"
    echo file \'"${ln_file}"\' >>"${tmpalist}"
  done

  # shellcheck disable=SC2312
  (ffmpeg -codecs 2>/dev/null | grep libfdk_aac >/dev/null) \
    && aac_codec="libfdk_aac"

  # shellcheck disable=SC2312
  [ -z "${aac_codec}" ] \
    && (ffmpeg -codecs 2>/dev/null | grep libfaac >/dev/null) \
    && aac_codec="libfaac"

  [ -z "${aac_codec}" ] && aac_codec="aac"

  ffmpeg -loop 1 -i "${tmpimg}" -f concat -safe 0 -i "${tmpalist}" \
    -shortest -pix_fmt yuvj420p -c:a "${aac_codec}" -b:a 512k -ar 96k \
    -c:v libx264 -strict -2 out.mp4

  ret="$?"
  rm -rf "${tmpdir}"
  [ "${ret}" -ne 0 ] && exit "${ret}"
else
  shift 1                                  # remove -t from args
  identify "$1" >/dev/null 2>&1 && shift 1 # remove image from args
fi

rm -f out.txt
H=0
M=0
S=0
CS=0

for x in "$@"; do
  # shellcheck disable=SC2001
  nm=$(echo "${x}" | sed -e 's/\([[:digit:]]*\) \?[-. ] \?/\1. /')
  printf "[%02d:%02d:%02d] %s\n" "${H}" "${M}" "${S}" "${nm%.*}" >>out.txt

  # shellcheck disable=SC2312
  t=$(ffmpeg -i "${x}" 2>&1 | grep 'Duration:' | tr ',' ' ' | awk '{ print $2 }')
  t=$(echo "${t}" | tr ':.' ' ')
  t=${t// 0/ }
  t=("${t#0*}")

  H=$((t[0] + H))
  M=$((t[1] + M))
  S=$((t[2] + S))
  CS=$((t[3] + CS))

  if [ "${CS}" -ge 100 ]; then
    S=$((S + 1))
    CS=$((CS - 100))
  fi

  if [ "${S}" -ge 60 ]; then
    M=$((M + 1))
    S=$((S - 60))
  fi

  if [ "${M}" -ge 60 ]; then
    H=$((H + 1))
    M=$((M - 60))
  fi
done

exit 0
