#!/bin/bash

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

STORAGE_DIRECTORY="/media/storage/"

# This script needs some software packages:
# apt-get install mplayer2 vlc vlc-nox libav-tools

if [ ! -d "$STORAGE_DIRECTORY" ];then
  echo "$STORAGE_DIRECTORY does not exist."
  exit 1
fi

# first parameter should be the TV station
if [ $# -lt 1 ];then
  echo "Choose one TV station:"
  cut -f 1 -d ':' ~/.mplayer/channels.conf | grep -v "(Internet)" | sort
  exit 0
fi

function stopTelevision() {
  if [ "$(pgrep -f "mplayer dvb://")" != "" ];then
    kill -9 $(pgrep -f "mplayer dvb://")
  fi
  killall avconv vlc 2>/dev/null
}

if [ "$1" == "stop" ];then
  stopTelevision
  exit 0
fi

# check if tvheadend is running
if [ "$(pgrep tvhead)" != "" ];then
  echo "tvheadend running"
  sudo service tvheadend stop
fi

if [ ! -e /tmp/television ];then
  echo "Creating fifo"
  mkfifo /tmp/television
fi

stopTelevision

TV_STATION="$1"
ESCAPED_TV_STATION=$(echo "$TV_STATION" | sed 's|/|_|g')

filename="${STORAGE_DIRECTORY}/$(date "+%F_%H-%M-%S")_${ESCAPED_TV_STATION}.mpg"

# extract mpg from transport stream ts
avconv -y -i /tmp/television -acodec copy -vcodec copy "$filename" -loglevel panic < /dev/null > /dev/null 2>/tmp/avconv.error &

# record television to fifo
mplayer dvb://"$TV_STATION" -quiet -dumpstream -dumpfile /tmp/television < /dev/null > /dev/null 2>/tmp/mplayer.error &

# wait for the creation of the file
index=0
while true; do
  sleep 1
  let index++
  if [ $index -gt 30 ];then
    echo "No stream found"
    exit 1
  fi

  if [ -e "$filename" ];then

    # check that the file is bigger than 1 MB
    if [ $(stat -c"%s" "$filename") -gt 1000000 ]; then

      echo "Starting to stream ..."

      # stream over the network, TCP port 8080
      cvlc -A alsa "$filename" --sout '#standard{access=http,mux=mpeg,dst=:8080}' >/dev/null 2>/tmp/cvlc.error &
      exit 0

    fi
  fi
done
