#!/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"

  pf=12
  vf=24

  mkdir tmp_videos
  mkdir tmp_metadata
  mkdir tmp_pictures

  rm -f tmp_pictures/*
  rm -f tmp_videos/*
  rm -f tmp_metadata/*

  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


  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"
  mv -f 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
    datetime="${pict/public_html\/pictures\/hehe-/}"
    datetime="${datetime/.jpg/}"
    Y="${datetime:0:4}"
    m="${datetime:4:2}"
    d="${datetime:6:2}"
    h="${datetime:9:2}"
    min="${datetime:11:2}"
    sec="${datetime:13:2}"
    datetime="$Y-$m-$d $h:$min:$sec"
    datetime="${datetime/ /T}"
    # echo "datetime : $datetime"
    # datetime= $($datetime | awk /([0-9]{4})([0-9]{2})([0-9]{2})-([0-9]{2})([0-9]{2})([0-9]{2})/ {print $1-$2-$3T$4:$5:$6})
    # 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))

    frame="\t\t{\"src\":\"$src\", \"datetime\":\"$datetime\", \"gps\":\"$gps\", \"currenttime\":\"$currenttime\", \"id\":\"$f\"}"
    if [[ $f != $(($l-1)) ]]; then
      frame="$frame,"
    fi

    echo -e "$frame" >> tmp_metadata/frames.json

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

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

  mv -f tmp_metadata/* public_html/metadata/


}


while true; do
    day=$(date +"%Y-%m-%d")
    logfile="logs/convert-$day.log"
    touch $logfile
    convert | tee -a $logfile
    sleep 10m
done
