#!/bin/sh

CHANNELS_CONF=/var/lib/vdr/channels.conf
CHANNEL_SETTINGS_DIR=/etc/vdr/plugins/iptv/vlcinput/

exit_with_error()
{
    logger "vlc2iptv: error: $*"
    exit 1
}

read_arguments()
{
    [ $# -ne 2 ] && exit_with_error "Invalid parameter count '$#' $*"
    PARAMETER=$1
    PORT=$2
}

lookup_channel_and_pids()
{
    [ ! -e "$CHANNELS_CONF" ] && \
      exit_with_error "channels.conf not found ($CHANNELS_CONF)"

    local CHANNEL_RECORD=`grep "[:]S=[10][|]P=[10][|]F=EXT[|]U=vlc2iptv_raw_loop[|]A=$PARAMETER[:]I" $CHANNELS_CONF`
    [ -z "$CHANNEL_RECORD" ] && \
      exit_with_error "no iptv channel with parameter $PARAMETER found"

    CHANNEL_NAME=`echo $CHANNEL_RECORD | awk "-F[;,:]" '{print $1}'`
    VPID=`echo $CHANNEL_RECORD | awk -F: '{print $6}'`
    APID=`echo $CHANNEL_RECORD | awk -F: '{print $7}'`
    SPID=0
}

load_channel_configuration()
{
    local CHANNEL_SETTINGS_FILE="$CHANNEL_SETTINGS_DIR/$CHANNEL_NAME.conf"

    [ ! -e "$CHANNEL_SETTINGS_FILE" ] && \
      exit_with_error "No vlc input configuration for channel '$CHANNEL_NAME'"
    . "$CHANNEL_SETTINGS_FILE"

    [ -z "$URL" ] && \
      exit_with_error "No URL specified for channel '$CHANNEL_NAME'"
}

read_arguments $*
lookup_channel_and_pids
load_channel_configuration

LC_NUMERIC=C vlc "${URL}" \
  --loop --sout-keep \
  --sout "#gather:duplicate{dst=std{access=udp,mux=ts{pid-video=${VPID},pid-audio=${APID},pid-spu=${SPID}},dst=127.0.0.1:${PORT}}}" \
  --intf dummy &
PID=${!}

trap 'kill -INT ${PID} 2> /dev/null' INT EXIT QUIT TERM
wait ${PID}
