#! /bin/bash

# DESCRIPTION:
#   Converting JPEG collection to MP4.
#   This is only a local "proof of conept" for testing and debugging.
#
# DEPENDENCIES:
#   - ffmpeg
#
# PARAMETERS:
#   1: "qn" - execution without pauses
#   2: custom configuration file path
#   3: periods: '' - today | '-d' - yesterday | '-w' - last week | '-m' - last month | '-y' - last year
#
# FUNCTIONS:
#

#######################################
# Print message and add to log.
# Globals:
#   logs
# Arguments:
#   1: message to print and logging
#######################################
addtologs() {
  echo "$(date +'%Y.%m.%d-%H:%M:%S') $1" | tee -a "${logs}"
}

#######################################
# Waiting for press [ENTER].
# Globals:
#   None
# Arguments:
#   None
#######################################
execpause() {
  read -r -p "Press [ENTER] to continue... "
}

#######################################
# Exit procedure.
# Globals:
#   show
# Arguments:
#   None
#######################################
execquite() {
  addtologs "execution time is $(($(date +%s)-time)) seconds, exit"
  if [ "${show}" != "qn" ]; then
  execpause
  fi
  exit
}

#######################################
# Error exit procedure with Telegram notification.
# Globals:
#   telegramapiurl
#   telegramchatid
# Arguments:
#   1: message to print and logging
#######################################
execerror() {
  addtologs "error: $1"
  curl -s -X POST "${telegramapiurl}/sendMessage" \
  -d "chat_id=${telegramchatid}" \
  -d "text=$(basename -s .sh "$0") error: $1" \
  >> /dev/null 2>&1
  execquite
}

#######################################
# Parsing config file and creating global vars.
# Globals:
#   None
# Arguments:
#   None
#######################################
getconfig() {
  logs=$(grep "logs=" "${conf}" | cut -d= -f2)
  list=$(grep "list=" "${conf}" | cut -d= -f2)
  imgroot=$(grep "imgroot=" "${conf}" | cut -d= -f2)
  IFS=" " read -r -a imgnames <<< "$(grep "imgnames=" "${conf}" | cut -d= -f2)"
  xscale=$(grep "xscale=" "${conf}" | cut -d= -f2)
  yscale=$(grep "yscale=" "${conf}" | cut -d= -f2)
  mp4fps=$(grep "mp4fps=" "${conf}" | cut -d= -f2)
  telegramapiurl=$(grep "telegramapiurl=" "${conf}" | cut -d= -f2)
  telegramchatid=$(grep "telegramchatid=" "${conf}" | cut -d= -f2)
}

#
# VARIABLES:
#

show=$1
conf=$2
if [ -z "${conf}" ] || [ "${conf}" == "-" ]; then
  conf="$(dirname "$(realpath "$0")")/$(basename -s .sh "$0").conf"
fi
when=$3
if [ -z "${when}" ]; then
  d=$(date +"%d")
  w=$(date +"%V")
  m=$(date +"%m")
  y=$(date +"%Y")
  duration=1
  imgpath="${y}/${m}/${w}/${d}"
  imgname="${y}.${m}.${d}"
fi
if [ "${when}" == "-d" ]; then
  d=$(date -d "-1 day" +"%d")
  m=$(date +"%m")
  if [ "$(date -d '-1 day' +'%m')" != "$(date +'%m')" ]; then
    m=$(date -d '-1 day' +'%m')
  fi
  y=$(date +"%Y")
  if [ "$(date -d '-1 day' +'%Y')" != "$(date +'%Y')" ]; then
    y=$(date -d '-1 day' +'%Y')
  fi
  w=$(date +"%V")
  if [ "$(date +'%w')" == "1" ]; then
    w=$(date -d "-1 week" +"%V")
  fi
  duration=1
  imgpath="${y}/${m}/${w}/${d}"
  imgname="${y}.${m}.${d}"
fi
if [ "${when}" == "-w" ]; then
  w=$(date -d "-1 week" +"%V")
  m=$(date +"%m")
  if [ "$(date -d '-1 week' +'%m')" != "$(date +'%m')" ]; then
    m=$(date -d '-1 week' +'%m')
  fi
  y=$(date +"%Y")
  if [ "$(date -d '-1 week' +'%Y')" != "$(date +'%Y')" ]; then
    y=$(date -d '-1 week' +'%Y')
  fi
  duration=7
  imgpath="${y}/*/${w}"
  imgname="${y}-w${w}"
fi
if [ "${when}" == "-m" ]; then
  m=$(date -d "-1 month" +"%m")
  y=$(date +"%Y")
  if [ "$(date -d '-1 month' +'%Y')" != "$(date +'%Y')" ]; then
    y=$(date -d '-1 month' +'%Y')
  fi
  duration=30
  imgpath="${y}/${m}"
  imgname="${y}.${m}"
fi
if [ "${when}" == "-y" ]; then
  y=$(date -d "-1 year" +"%Y")
  duration=360
  imgpath="${y}"
  imgname="${y}"
fi

time=$(date +%s)
cd "$(dirname "$(realpath "$0")")" || execerror
if [ ! -e "${conf}" ]; then
  execerror "Not found config file: ${conf}"
else
  getconfig
fi
if [ -z "${logs}" ];then
  logs=/dev/null
elif [ ! -e "${logs}" ];then
  touch "${logs}"
fi
if [ -z "${list}" ];then
  list="$(dirname "$(realpath "$0")")/$(basename -s .sh "$0").list"
fi
if [ ! -e "${list}" ];then
  touch "${list}"
fi
if ! command -v ffmpeg &> /dev/null; then
  execerror "Not found dependencies"
fi

#
# MAIN:
#

for name in "${imgnames[@]}"; do
  imgmatch="*${name}*.jpeg"
  imgarray=()
  while read -r FILE; do
    imgarray+=("${FILE}")
  done < <(find "${imgroot}/${imgpath}" -name "${imgmatch}" | sort)
  imgcount=${#imgarray[*]}

  echo '' > "${list}"
  for item in "${imgarray[@]}"; do
    echo file \'"${item}"\' >> "${list}"
  done

  imgdest="${imgroot}/${name}_${imgname}.mp4"
  echo "${imgdest}"
  if ffmpeg -r "${imgcount}/${duration}" -f concat -safe 0 -i "${list}" \
    -c:v libx264 -vf "scale=${xscale}:${yscale},fps=${mp4fps},format=yuv420p" \
	"${imgdest}" -y; then
    addtologs "converted ${imgcount} images to ${imgdest} with duration ${duration}"
  else
    execerror "converted ${imgcount} images to ${imgdest} with duration ${duration}"
  fi
done
execquite
