#!/bin/bash
DIR="$(dirname "$(realpath --logical --no-symlinks "${BASH_SOURCE[0]}")" )"  # don't follow, link location (not target) matters

PARAM_MAX_HEIGHT_DEFAULT=1080
PARAM_MAX_HEIGHT="${1:-"${PARAM_MAX_HEIGHT_DEFAULT}"}"

DIR_IN="$(realpath --logical --no-symlinks "${2:-"${DIR}/1-input"}")"
DIR_DONE="$(realpath --logical --no-symlinks "${3:-"${DIR}/2-done"}")"
DIR_OUT="$(realpath --logical --no-symlinks "${4:-"${DIR}/3-output"}")"

PARAM_MIN_BYTERATE="250000"  # 250 KBps = 2 Mbps = aprox. 1,8GB for 2h movie


codec() { ffprobe -v error -select_streams v:0 -show_entries stream=codec_name -of csv=p=0 "${1}"; }
brate() { expr $(stat -c %s "${1}") / $(ffprobe -v error -select_streams v:0 -show_entries format=duration -of csv=p=0 "${1}" | awk '{print int($1)}'); }

do_recode() {
  echo "RECODE: ${1}"
  OUTF="${DIR_OUT}/${2}";  mkdir --parents "$(dirname "${OUTF}")"
  bash "${DIR}/recode-vid-single.sh"  "${1}" "${PARAM_MAX_HEIGHT}" "${OUTF}"
  PROCESS_SUCCESS=$?
}

do_copy() {
  OUTF="${DIR_OUT}/${2}";  mkdir --parents "$(dirname "${OUTF}")"
  if [[ $(stat -c %d "${1}") -eq $(stat -c %d "$(dirname "${OUTF}")") ]]; then LINK="-l"; echo -n "LINK-"; fi
  cp ${LINK}  "${1}" "${OUTF}"
  echo "COPY: ${1}"
  PROCESS_SUCCESS=$?
  sleep 5s
}


while true; do   # Loop through each file, copy or recode as needed, then move original to done dir

  readarray -d $'\0' INPUTS < <(find "${DIR_IN}" -type f -printf "%P\0" | sort --zero-terminated)
  IN_FILENAME="${INPUTS[0]}"

  if [[ -n "${IN_FILENAME}" ]]; then  SLEPT=0
    IN_FILE="${DIR_IN}/${IN_FILENAME}"

    if [[ "$(file --brief --mime-type "${IN_FILE}")" == "video/"* ]] && [[ " sub " != *" ${IN_FILENAME##*.} "* ]]; then
      if [[ "$(codec "${IN_FILE}")" != "hevc" ]]; then
        do_recode "${IN_FILE}" "${IN_FILENAME%.*}.mp4"
      else
        if [[ "$(brate "${IN_FILE}")" -gt "${PARAM_MIN_BYTERATE}" ]]
          then do_recode "${IN_FILE}" "${IN_FILENAME%.*}.mp4"
          else do_copy "${IN_FILE}" "${IN_FILENAME}"
        fi
      fi
    else  do_copy "${IN_FILE}" "${IN_FILENAME}";  fi

    if [[ ${PROCESS_SUCCESS} -eq 0 ]]; then
      DONE_FILE="${DIR_DONE}/${IN_FILENAME}";  mkdir -p "$(dirname "${DONE_FILE}")";  mv "${IN_FILE}" "${DONE_FILE}"
      pushd "${DIR_IN}" &>/dev/null;  rmdir -p --ignore-fail-on-non-empty "$(dirname "${IN_FILENAME}")";  popd &>/dev/null
    else  break;  fi  # break loop when fail

  else  { [[ ${SLEPT} -eq 0 ]]  &&  echo "NOTHING TO DO AT: $(date --iso-8601=minutes)"; };  SLEPT=1;  sleep 5m;  fi

done

