#!/bin/bash

#SAT_IP_SERVER=192.168.x.y
SAT_IP_SERVER=fqdn.of.satip.server          # IP or FQDN of the SAT>IP Server
GIT_LOCAL_REPO=/srv/sw/satip                # where should the local GIT repository be located
GIT_REPO="https://code.google.com/p/satip"  # URL of the SAT>IP - VTUNER repository


if [ -z "$SAT_IP_SERVER" ]; then
  echo "Please define your SAT>IP Server at the beginning of this script"
  exit 1
fi

NUM_INSTANCES=1
if [ ! -z "$1" ]; then
  if [ "$1" -lt "4" ]; then
    if [ "$1" -gt "0" ]; then
      NUM_INSTANCES=$1
    fi
  fi
fi

if [ ! -d $GIT_LOCAL_REPO ]; then
  echo "Trying to git clone $GIT_REPO"
  cd `dirname $GIT_LOCAL_REPO`
  if [ -x /usr/bin/git ]; then
    /usr/bin/git clone $GIT_REPO
  else
    echo "GIT not installed. Unable to get clone remote SATIP repo"
    exit 1
  fi
fi

# compile SATIP Application
cd $GIT_LOCAL_REPO/satip
make clean
make

# compile vtuner kernel module
cd $GIT_LOCAL_REPO/vtuner_tweak
make clean
make

# load vtuner kernel module 
if lsmod | grep -q vtunerc; then
  modprobe -r vtunerc
fi
mkdir -p /lib/modules/`uname -r`/kernel/drivers/media/tuners
cp vtunerc.ko /lib/modules/`uname -r`/kernel/drivers/media/tuners/vtunerc.ko
depmod -a
modprobe vtunerc devices=$NUM_INSTANCES debug=0
sleep 1
chmod a+rw /dev/vtunerc*
for i in $(seq 0 $(($NUM_INSTANCES-1))); do
  chmod a+rw /dev/dvb/adapter$i/*
done

# run x instances of SATIP Application in the background
for i in $(seq 0 $(($NUM_INSTANCES-1))); do
  $GIT_LOCAL_REPO/satip/satip -h $SAT_IP_SERVER -d /dev/vtunerc$i 2>&1 >/dev/null &
done

# start/restart vdr --> vtuners are recognized
#if status vdr | grep -q "^vdr start"; then
#  restart vdr
#else
#  start vdr
#fi

