#!/bin/bash
# Bachir Soussi Chiadmi 06/2016
# https://trac.ffmpeg.org/wiki/Create%20a%20video%20slideshow%20from%20images
# needs ffmep and exiftool

function convert {

  now=$(date +"%Y-%m-%d--%T")
  echo "Timelaps conversion | $now"

  mkdir tmp_videos
  mkdir tmp_metadata
  mkdir tmp_pictures

  rm -f tmp_pictures/*

  x=1
  for i in public_html/pictures/*.jpg; do
    counter=$(printf %06d $x)
    ln "$i" tmp_pictures/img"$counter".jpg
    x=$(($x+1))
  done

  pf=12
  vf=24

  echo "pictframerate:$pf, videoframerate=$vf"

  echo 'Video conversion'
  echo "creating raw timelaps"
  ffmpeg -y \
    -framerate $pf \
    -i tmp_pictures/img%06d.jpg \
    -r $vf -pix_fmt yuv420p -vcodec libx264 \
    tmp_videos/timelaps-raw.mp4

  echo "optimizing responsive videos"
  ffmpeg -y -i tmp_videos/timelaps-raw.mp4 -vf "scale=1920:-1, crop=in_w:1080" tmp_videos/timelaps-1080p.mp4
  ffmpeg -y -i tmp_videos/timelaps-raw.mp4 -vf "scale=1280:-1, crop=in_w:720" tmp_videos/timelaps-720p.mp4
  ffmpeg -y -i tmp_videos/timelaps-raw.mp4 -vf "scale=720:-1, crop=in_w:480" tmp_videos/timelaps-480p.mp4
  ffmpeg -y -i tmp_videos/timelaps-raw.mp4 -vf "scale=640:-1, crop=in_w:340" tmp_videos/timelaps-360p.mp4
  ffmpeg -y -i tmp_videos/timelaps-raw.mp4 -vf "scale=360:-1, crop=in_w:240" tmp_videos/timelaps-240p.mp4

  echo "updating production videos"
  rsync -r tmp_videos/ public_html/videos/

  echo "metadata export"
  l=0
  for pict in public_html/pictures/*.jpg; do
    l=$((l+1))
  done
  f=0
  echo -e '{' > tmp_metadata/frames.json
  echo -e '\t"frames":[' >> tmp_metadata/frames.json

  for pict in public_html/pictures/*.jpg; do
    # SRC
    src="${pict/public_html\/pictures\//}"
    # TIME
    # time="${pict/public_html\/pictures\/hehe-/}"
    # time="${time/.jpg/}"
    datetime=`exiftool 2>/dev/null -S --DateTimeOriginal -p '$DateTimeOriginal' -d %Y-%m-%dT%T "$pict"`
    # GPS
    gps=`exiftool 2>/dev/null -n -p '$GPSLatitude,$GPSLongitude' $pict`

    # FRAME
    currenttime=$(((1/$pf)*$f))

    if [[ $f == $(($l-1)) ]]; then
      echo -e "\t\t{\"src\":\"$src\", \"datetime\":\"$datetime\", \"gps\":\"$gps\", \"currenttime\":\"$currenttime\"}" >> tmp_metadata/frames.json
    else
      echo -e "\t\t{\"src\":\"$src\", \"datetime\":\"$datetime\", \"gps\":\"$gps\", \"currenttime\":\"$currenttime\"}," >> tmp_metadata/frames.json
    fi

    f=$(($f+1))
  done

  echo -e '\t]' >> tmp_metadata/frames.json
  echo -e '}' >> tmp_metadata/frames.json

  rsync -r tmp_metadata/ public_html/metadata/


}



day=$(date +"%Y-%m-%d")
logfile="logs/convert-$day.log"
touch $logfile
convert | tee -a $logfile
