#!/bin/sh

################################
## Script to configure freevo ##
################################

DESTINATION="/root"
SAVE_CONF="$DESTINATION/save"
DEST_CONF="$DESTINATION/.freevo"
TMP="$DESTINATION/tmp"
LOG_F="$DESTINATION/freevo-config-$(date +%Y%m%d%H%M).txt"

mkdir -p $SAVE_CONF
mkdir -p $DEST_CONF
mkdir -p $TMP
mkdir -p /root/.mplayer
mkdir -p /root/.xine

# saving freevo configuration files
freevo setup 1>>$LOG_F
cp /etc/freevo/freevo.conf $SAVE_CONF/freevo.conf-origin
cp /etc/freevo/local_conf.py $SAVE_CONF/local_conf.py-origin

# functions

search_resolution () {
  local list
  list=""
  for i in `xrandr 2>/dev/null`; do
  list="$list `echo $i | grep "....x....\|....x...\|...x..." | grep -v + `"
  done
  echo $list
}

gen_e () {
 local e
 local count
 e="" 
 count=1
 for i in $1 ; do
   l="$l $count $i"
   count=$(($count+1))
 done
 echo $l
}

update_names_in_f () {
  local name 
  local new_name
  local f
  name=$1
  new_name=$2
  f=$3
  catv "$f" | sed -e "s/$name/$new_name/" >$TMP/fich-temp
  cp $TMP/fich-temp $f
}
# change screen resolution
possible_resolution=`search_resolution`
e=`gen_e "$possible_resolution"`
dialog --title "Choose your resolution" \
       --menu "You have choice between :" 20 70 5 \
        $e 2> $TMP/choosen-resolution

  case $? in
      0)
        pos=$(cat "$TMP/choosen-resolution" )
        resolution="`echo $possible_resolution | cut -d" " -f$pos`"
        new_geometry=$(echo geometry = $resolution)
        grep -v geometry $SAVE_CONF/freevo.conf-origin > $SAVE_CONF/freevo.conf
        echo $new_geometry >>$SAVE_CONF/freevo.conf
        echo $new_geometry >>$LOG_F
        cp $SAVE_CONF/freevo.conf $DEST_CONF
        ;;
      1)
        exit 0
        ;;
      255)
        exit 0
        ;;
  esac

# ensure that dvbstreamer is present in conf
echo "dvbstreamer = /usr/bin/dvbstreamer" >> $SAVE_CONF/freevo.conf

# config of DVB : assuming playing by mplayer/xine

dialog --title " DVB configuration" --clear \
       --yesno "Do you want to scan for channels ?" 10 30

  case $? in
      0)
        lang=`cat /etc/locale.conf | cut -d"_" -f2 | cut -d"." -f1`      
        dialog --infobox "Please wait while scanning \
                          \n Be patient \
                          \n (20 min, take a coffee ;) )" 15 30 ;
        w_scan -c $lang -ft -X > $SAVE_CONF/channels.conf-after-scan 2>>$LOG_F
        ;;
      1)
        dialog --title "Select a valid channel.conf" --fselect $DESTINATION/ 14 48 2>$TMP/f_select
        case $? in
            0)
              cp `cat $TMP/f_select` $SAVE_CONF/channels.conf-after-scan
              ;;
            1)
              echo "Cancel by user" >>$LOG_F
              exit 0
              ;;
            255)
              echo "Cancel by user" >>$LOG_F
              exit 0
              ;;
        esac
        ;;
      255)
        echo "Cancel by user" >>$LOG_F
        exit 0
        ;;
  esac

# replace space ( and ) by _ and name a special caracter :; after first :
sed 's/ /_/g' $SAVE_CONF/channels.conf-after-scan | sed 's/(/_/' | sed 's/)/_/' >$SAVE_CONF/channels.conf-after-scan2
NB_channels=`wc -l $SAVE_CONF/channels.conf-after-scan2 | cut -d" " -f1`

if [ "$NB_channels" != "0" ] ; then 
  dialog --infobox "Ok, Found $NB_channels channels" 10 30 ; sleep 1
else
  dialog --infobox "??, No channel found, Exiting" 10 30 ; sleep 2 && exit 1
fi 

# Tweaking channels.conf

list_names_e=`catv $SAVE_CONF/channels.conf-after-scan2 | awk -F ":" '{print $1 " "$1}'`

boucle=0
while [ "$boucle" = "0" ] ; do

value="$(dialog --stdout --clear --ok-label "apply" \
       --inputmenu "You can change name's stations. If you want to unactivate one, \
                    just add a # before the name" 30 60 20 $list_names_e )"

  case $? in
      3)
        echo "$value" >> /root/test.txt
        name=`echo $value | cut -d" " -f2`
        new_name=`echo $value | cut -d" " -f3`
        update_names_in_f "$name" "$new_name" "$SAVE_CONF/channels.conf-after-scan2"
        list_names_e=`catv $SAVE_CONF/channels.conf-after-scan2 | awk -F ":" '{print $1 " "$1}'`
        boucle=0
        ;;
      0)
        boucle=1
        ;;
      1)
        boucle=1
        ;;
      255)
        exit 1
        ;;
  esac

done

cp $SAVE_CONF/channels.conf-after-scan2 $SAVE_CONF/channels.conf2


# Installing channels.conf for Mplayer and Xine ...
dialog --infobox "Installing channels.conf for Mplayer and Xine ..." 10 30 ;
cp $SAVE_CONF/channels.conf2 /root/.mplayer/channels.conf
cp $SAVE_CONF/channels.conf2 /root/.xine/channels.conf
cat $SAVE_CONF/channels.conf2 >> $LOG_F

dialog --infobox "Writing configuration to files ..." 10 30 ;

# Generating conf for TV
cat >$SAVE_CONF/local_conf.py <<EOF
MPLAYER_ARGS['dvb']     = '-cache 4096'
TV_VIDEO_GROUPS = [
    VideoGroup(vdev='0',
               adev=None,
               input_type='tuner',
               input_num=1,
               group_type = 'dvb',
               record_group=None,
               desc='DVB Viewer'),
]

TV_CHANNELS = [
#   ( 'XMLTV NAME', 'FREEVO DISPLAY NAME', 'CHANNELS.CONF NAME' ),
EOF

NB_channels=`wc -l $SAVE_CONF/channels.conf2 | cut -d" " -f1`
j=1
while read i
do
  station_name="`echo $i | cut -d":" -f1`"
  if [ "$j" != "$NB_channels" ];then
    echo "( '$station_name', '$station_name', '$station_name')," >> $SAVE_CONF/local_conf.py
    j=$(($j+1))
  else 
    echo "( '$station_name', '$station_name', '$station_name')" >> $SAVE_CONF/local_conf.py
    echo "]" >> $SAVE_CONF/local_conf.py
  fi
done < $SAVE_CONF/channels.conf2

# End TV conf

# Config recordserver
dialog --title "Config for recordserver" --clear \
       --yesno "Do you want to enable recordserver ?" 10 30

  case $? in
      0)
        dialog --title "size for cache ?" --clear --inputbox "Choose the size in Mb for livepause buffer :" 10 30 "512" 2>$TMP/result
          case $? in
              0)
                result=`cat $TMP/result`
                cat >>$SAVE_CONF/local_conf.py <<EOF
VCR_CMD = CONF.mplayer + ' -dumpstream -dumpfile %(filename)s "dvb://%(channel)s"' + '& sleep %(seconds)s ; kill \$!'
TV_RECORD_FILE_SUFFIX = '.ts'
RECORDSERVER_IP = '127.0.0.1'
plugin.remove('tv.mplayer')
plugin.activate('tv.livepause')
plugin.remove('tv.generic_record')
plugin_record = plugin.activate('tv.dvbstreamer.record')
LIVE_PAUSE2_BUFFER_PATH='/tmp/ramdisk/live.buf'
LIVE_PAUSE2_PREFERRED_PLAYER='mplayer'
EOF
mkdir -p /tmp/ramdisk
mount -t tmpfs -o size=${result}M,mode=0777 tmpfs /tmp/ramdisk
echo "tmpfs /tmp/ramdisk tmpfs size=${result}M,mode=0777 0 0" >>/etc/fstab
echo "LIVE_PAUSE2_BUFFER_SIZE= $result" >>$SAVE_CONF/local_conf.py
                 dialog --infobox "Recordserver and livepause enabled ..." 10 30 ;
                 sleep 1
                ;;
              1)
                exit 0
                ;;
              255)
                exit 1
                ;;
          esac
        ;;
      1)
        exit 0
        ;;
      255)
        exit 1
        ;;
  esac 

# End config recordserver

cat $SAVE_CONF/local_conf.py-origin > $DEST_CONF/local_conf.py
cat $SAVE_CONF/local_conf.py >> $DEST_CONF/local_conf.py


# dvbstreamer : database init
dialog --infobox "dvbstreamer Daemon and database init ..." 10 30 ;
sleep 1
setupdvbstreamer -t $SAVE_CONF/channels.conf2

# end
dialog --infobox "All done ..." 10 30 ;
sleep 1
exit 0
