#!/bin/bash

# author: Torsten Tränkner
# version: 0.1
# license: GPLv2

STORAGE_DIRECTORY="/media/storage/"
DEFAULT_URL="http://tagesschau-lh.akamaihd.net/z/tagesschau_1@119231/manifest.f4m"

# stream: 7 MB in 20 seconds
MINIMUM_DIFFERENCE=1000000
FILE_CHECK_SECONDS=20

# This script needs some software packages:
#
# sudo apt-get install -y php5 php5-cli php5-mcrypt php5-curl curl
#
# On some systems you have to enable the mcrypt module for php:
# sudo php5enmod mcrypt

# check that download script is available
if [ ! -e AdobeHDS.php ];then

  # use fixed version instead of latest version
  wget -q "https://raw.githubusercontent.com/K-S-V/Scripts/7e1c8d844e9907ea6407d74bc1d784e71ccb3ca3/AdobeHDS.php"

  # wget "https://raw.githubusercontent.com/K-S-V/Scripts/master/AdobeHDS.php"

fi

filename=""

function log() {
  x=0
  # echo "$1"
}

function downloadTagesschau() {
  rm -f livestream.txt

  wget http://www.tagesschau.de/templates/pages/multimedia/livestream_player.jsp -O livestream.txt
  manifestUrl=$(grep "manifest\.f4m" livestream.txt | sed 's|.*\(http:.*\.f4m\).*|\1|')

  date >> ~/ard_urls.txt

  if [ "$manifestUrl" == "" ];then
    echo "video URL not found, using default" >> ~/ard_urls.txt
    manifestUrl="$DEFAULT_URL"
  fi

  echo "$manifestUrl" >> ~/ard_urls.txt

  # download the stream
  filename="${STORAGE_DIRECTORY}"/$(date "+%F_%H-%M-%S")_tagesschau.flv
  php AdobeHDS.php --manifest "${manifestUrl}?hdcore=3.1.0&plugin=aasp-3.1.0.43.124" --delete --outfile "$filename" > /tmp/tagesschau.txt 2>&1 &

  return 0
}

# check that the file is written constantly - until this script is killed
function supervision() {
  echo "$filename"

  if [ -e "$filename" ]; then
    old_filesize=$(stat -c%s "$filename")
  else
    old_filesize=0
  fi

  while true; do
    sleep $FILE_CHECK_SECONDS

    if [ -e "$filename" ]; then
      filesize=$(stat -c%s "$filename")
    else
      filesize=0
    fi
    let difference=filesize-old_filesize

    log "Difference in byte: $difference"

    if [ $difference -lt $MINIMUM_DIFFERENCE ];then
      echo "Difference is less than $MINIMUM_DIFFERENCE"
      return 0
    fi

    old_filesize=$filesize
  done
}

retry_counter=0

# number of seconds to wait for a retry
RETRY_TIME=10
MAX_COUNTER=50

while [ $retry_counter -lt $MAX_COUNTER ]; do
  echo "Retrycounter: $retry_counter"
  downloadTagesschau
  result=$?
  echo "Return code: $result"
  if [ $result -eq 0 ]; then
    supervision
  else
    # wait some seconds then try again
    echo "Retrying in $RETRY_TIME seconds ..."
    sleep $RETRY_TIME
  fi
  killall php
  let retry_counter++
done

echo "No success. Giving up."
