#!/bin/bash
# This is dxr3config by Wicky
# for requests and suggestions send a pn to Wicky @ www.vdrportal.de

version="0.3.4"
title="dxr3config Version $version"

TMPPATH=/tmp

#Path to dxr3config.m2v
M2VPATH=/usr/share/dxr3config

# With this parameter you can selcet for which Distribution you want to use dxr3config
# This changes the way dxr3config saves the modulparameters
# See function setDISTsettings, save and makeModprobe for more Informations
#
# supported values: linvdr0-7, linvdr0-8, gentoo, debian
#DIST="linvdr0-7"
#DIST="linvdr0-8"
#DIST="gentoo"
DIST="debian"

# Dont edit this presets, use the skript parameters instead!!
modify="false"
auto="false"
genScripts="false"
paramSet=0
eepromInfo="no eeprom info needed for this card"

# Wicky
#set -e
trap 'echo "Good bye..."; quit 0' 0
trap 'echo "Good bye..."; stopMpeg; quit 8' 2 3 15

typeset -i paramSet
advParam[1]="adv717x pixelport_16bit=1 pixelport_other_pal=1"
emParam[1]="em8300 dicom_fix=1 dicom_control=1 dicom_other_pal=1"

advParam[2]="adv717x pixelport_16bit=0 pixelport_other_pal=0"
emParam[2]="em8300 dicom_fix=1 dicom_control=1 dicom_other_pal=0"

advParam[3]="adv717x pixelport_16bit=0 pixelport_other_pal=1"
emParam[3]="em8300 dicom_fix=1 dicom_control=1 dicom_other_pal=1"

advParam[4]="adv717x pixelport_16bit=1 pixelport_other_pal=0"
emParam[4]="em8300 dicom_fix=0 dicom_control=0 dicom_other_pal=0"

advParam[5]=""
emParam[5]=""

advParam[6]=""
emParam[6]=""

advParam[7]=""
emParam[7]=""

advParam[8]=""
emParam[8]=""

advParam[9]=""
emParam[9]=""

advParam[10]="bt865"
emParam[10]="em8300 dicom_fix=1 dicom_control=1 dicom_other_pal=1 use_bt865=1"

advParam[11]="bt865"
emParam[11]="em8300 dicom_fix=1 dicom_control=1 dicom_other_pal=1 use_bt865=1 bt865_ucode_timeout=1"

advParam[12]="bt865"
emParam[12]="em8300 dicom_fix=1 dicom_control=1 dicom_other_pal=0 use_bt865=1 bt865_ucode_timeout=1"

advParam[13]="bt865"
emParam[13]="em8300 dicom_fix=0 dicom_control=0 dicom_other_pal=0 use_bt865=1 bt865_ucode_timeout=1"

advParam[14]=""
emParam[14]=""

advParam[15]=""
emParam[15]=""


redblueParam[2]="pixeldata_adjust_pal=0"
redblueParam[3]="pixeldata_adjust_pal=1"
redblueParam[4]="pixeldata_adjust_pal=2"
redblueParam[5]="pixeldata_adjust_pal=3"
redblueParam[6]="pixeldata_adjust_ntsc=0"
redblueParam[7]="pixeldata_adjust_ntsc=1"
redblueParam[8]="pixeldata_adjust_ntsc=2"
redblueParam[9]="pixeldata_adjust_ntsc=3"

adapterParam[1]="output_mode=comp+svideo"
adapterParam[2]="output_mode=comp+psvideo"
adapterParam[3]="output_mode=psvideo"
adapterParam[4]="output_mode=composvideo"
adapterParam[5]="output_mode=yuv"

adapter=""
redblue=""

eepromOut[1]="000010039b8609956173301dcbb5f6818cc6b63"
eepromOut[2]="0000100a973a45afbf42a8f646b9971ffd3d7d4"

cleanupfiles="
playM2V.sh
dxr3config.tmp
dxr3info.txt
tmp.m2v"

#playM2V.stop
#emptyModprobe.conf

# Set Cursur Position Commands, used via echo -e
COL=50
SET_COL="\\033[${COL}G"

# Set color commands, used via echo -e
NORMAL="\033[0m"
SUCCESS="\033[0;32m"
WARNING="\033[0;33m"
FAILURE="\033[0;31m"

function quit () 
{
        OLDIFS=$IFS
        IFS=$'\t'$'\n'
        for files in $cleanupfiles; do
                IFS=$OLDIFS
                if [ -w $TMPPATH/$files ]; then
                        rm $TMPPATH/$files
                fi
        done
        exit $1;
}



function setDistSettings ()
{
        case $DIST in
                linvdr0-7)      genModprobe="false";
                                scriptsPath="/etc/init.d"
                                genScripts="true";;
                linvdr0-8)      genModprobe="true";
                                modify="true";
                                moduleFile="/etc/modprobe.conf";;
                debian)         genModprobe="true";
                                modify="false";
                                modprobed="/etc/modprobe.d";;
                gentoo)         genModprobe="true";
                                modify="false";
                                modprobed="/etc/modules.d";;
        esac
}

function usage ()
{
        echo ""
        echo "dxr3config $version"
        echo ""
        echo "dxr3config - a small tool to generate a dxr3 module configuration"
        echo ""
        echo "Options:"
        echo "        -a               non-interactive mode with hardwaredetection"
        echo "        -cp              lists dxr3configs adv717x/bt865 parameters"
        echo "        -ap              lists dxr3configs adapter parameters"
        echo "        -rbp             lists dxr3configs red/blue parameters"
	echo "        -alsa            audio_driver=alsa"
	echo "        -oss             audio_driver=oss (default)"
        echo "        -h               this message"
        echo ""
        echo "This options can/should only be used with --auto:"
        echo ""
        echo "        -mm              modifies modprobe.conf"
        echo "                         a copy of your modprobe.conf will be saved."
        echo "        -gm              generates a mod-utils compatible"
        echo "                         dxr3 configuration file in /etc/modprobe.d"
        echo "        -gs              generates load and unload scripts"
        echo "        -fbas            try this parameter if your picture is only black&white"
        echo "                         and you are using a S-VIDEO -> FBAS adapter"
        echo "                         there will be no effects if your dxr3 has bt865"
        echo "        -yuv             use this parameter for yuv"
        echo "                         there will be no effects if your dxr3 has bt865"
        echo ""
        echo "Examples:"
        echo ""
        echo "dxr3config -a            loads the dxr3-modules with the needed parameters"
        echo "dxr3config -a -yuv       loads the dxr3-modules with the needed parameters"
        echo "                         and configures your dxr3 for yuv"
        echo "dxr3config -a -gm        loads the dxr3-modules with the needed parameters"
        echo "                         and stores a modutils compatible file in /etc/modprobe.d/dxr3"
        echo "dxr3config -a -gs        loads the dxr3-modules with the needed parameters"
        echo "                         and generates load and unload scripts for the dxr3 modules"
        echo ""

}

function printChipParam ()
{
        echo "adv717x and bt865 Parameters:"
        echo ""
        for i in 1 2 3 4;  do
                echo "Parameterset $i:         modprobe ${advParam[i]}"
                echo "Parameterset $i:         modprobe ${emParam[i]}"
                echo ""
        done
        for i in 10 11 12 13;  do
                echo "Parameterset $i:        modprobe ${advParam[i]}"
                echo "Parameterset $i:        modprobe ${emParam[i]}"
                echo ""
        done
}

function printAdapterParam ()
{
        echo "dxr3config adapter parameters:"
        for i in 1 2 3 4 5; do
                echo ""
                echo "Adapter parameter $i:        ${adapterParam[i]}"
        done
        echo ""
}

function printRedBlueParam ()
{
        echo "dxr3config red/blue parameters:"
        for i in 1 2 3 4 5 6 7 8 9; do
                echo ""
                echo "red/blue parameter $i:        ${redblueParam[i]}"
        done
        echo ""
}

# read script parameter
while [ $# -gt 0 ]; do
        case $1 in
                --auto|-a)              auto="true";
                                        shift;;
		-alsa|--alsa)		audio_driver="alsa";
					shift;;
		-oss|--oss)		audio_driver="oss";
					shift;;
                --modModprobe|-mm)      modify="true"
                                        genModprobe="true";
                                        moduleFile="/etc/modprobe.conf"
                                        shift;;
                --genScripts|-gs)        genScripts="true"
                                        scriptsPath=$(pwd)
                                        shift;;
                --genModprobe|-gm)      genModprobe="true"
                                        modprobed="/etc/modprobe.d";
                                        shift;;
                --fbas|-fbas)           adapter=${adapterParam[2]};
                                        shift;;
                --YUV|-YUV)             adapter=${adapterParam[5]};
                                        shift;;
                --chipParam|-cp)        printChipParam;
                                        exit;;
                --adapterParam|-ap)     printAdapterParam;
                                        exit;;
                --redblueParam|-rbp)    printRedBlueParam;
                                        exit;;               
                        *)              usage;
                                        exit;;
        esac
done


function checkVDRrunning ()
{
        vdr=`ps | grep "vdr "`
        if [ -n "$vdr" ]; then
                if [ "$auto" = "true" ]; then
                        echo "";
                        echo "VDR is running. Stop it before running dxr3config."
                        echo "";
                        quit 2;
                else
                        msg "**** VDR is running ****\\nYou have to stop it before running dxr3config.";
                        quit 2;
                fi
        fi
}

function checkRoot ()
{
        if [ $(id -u) != "0" ]; then
                msg  "You are not loged in as user root.\\n **** dxr3config will not work ****\\nLogin as user root, before you use dxr3config.";
                quit 3;
        fi
}

echo_ok()
{
        echo -e "$1$SET_COL${SUCCESS}"[ "${2}" ]"$NORMAL"
}

echo_failure()
{
        echo -e "$1$SET_COL${FAILURE}"[ "${2}" ]"$NORMAL"
}

echo_warning()
{
        echo -e "$1$SET_COL${WARNING}"[ "${2}" ]"$NORMAL"
}

function manage_audio_driver()
{
    #Which soundsystem should be used? OSS or ALSA

    set_OSS="false"
    if [ $(echo $moduleVersion | grep -c 16) != 0 ] || [ $(echo $moduleVersion | grep -c 15.3cvs) != 0 ] ; then 
        set_OSS="true"
    fi    
    if [ -f /sys/module/em8300/parameters/audio_driver ]; then
        set_OSS="true"
    fi
    if [ x$audio_driver = "xalsa" ]; then
        set_OSS="false"
    fi
    if [ x$audio_driver = "xoss" ]; then
        set_OSS="true"
    fi
    #echo "audio_driver: $audio_driver"
    #echo "set_OSS: $set_OSS"
    if [ $set_OSS = "true" ]; then
	i=1;
	while [ $i -le 16 ]; do
	    emParam[$i]="${emParam[$i]} audio_driver=oss"
	    #echo ${emParam[$i]}
	    i=$((i+1))
	done;
    fi
}				    


function preCheck ()
{
        echo "Checking your dxr3 hard- and software........."
        echo ""
        rmmodules
	rmmodules
        # ********** Can the modules be load? **********
        for module in adv717x bt865 em8300; do
                if  modprobe -q $module; then
                        echo_ok "loading module $module" "OK"
                else
                        echo_failure "loading module $module" "FAILED"
                fi
        done

        # ************ hardware detection *************
        dxr3Rev=""
	dxr3Rev=$(lspci -n | grep 1105:8300 | awk '{print $NF}' | sed 's/(//g' | sed 's/)//g')
        if [ -n "$dxr3Rev" ]; then
                echo_ok "detecting dxr3-hardware" "OK"
                echo_ok "dxr3 hardware revision" "$dxr3Rev"
                advUsed="1";
                advUsed=$(grep "^adv717x" /proc/modules | awk '"$module" {print $3}')
                if [ "$advUsed" = "1" ]; then
                        echo_ok "detecting adv717x/bt865" "adv717x"
                        chip="adv717x"
                else
                        echo_ok "detecting adv717x/bt865" "bt865"
                        chip="bt865"
                fi

        else 
                echo_failure "detecting dxr3-hardware" "No dxr3 found"
        fi

        # ************ playing a mpeg to get more Infos...  *************
        startMpeg
        sleep 2
        setParamset
        echo_ok "Card revision:" "$cardRev"
        echo_ok "Chip revision:" "$chipRev"
        echo_ok "Video Encoder:" "$videoEncoder"
        echo_ok "Module Version:" "$moduleVersion"
	stopMpeg
	
        # ********* Is em8300setup available?
        if ! [ -z $(which em8300setup) ]; then
                em8300setupPath=$(which em8300setup);
        fi
        noEm8300setup="true";
        if [ "x$em8300setupPath" != "x" ]; then
                echo_ok "looking for em8300setup" "$em8300setupPath"
                if [ "$(em8300setup | grep 'xMicrocode uploaded')" != "" ]; then
                        echo_ok "looking for Microcode" "OK"
                        noEm8300setup="false";
                else
			rmmodules
			rmmodules
			modprobe bt865
			modprobe em8300 audio_driver=oss
			if [ "$(em8300setup | grep 'uploaded')" != "" ]; then
			    echo_ok "looking for Microcode" "OK"
			else
			    #new
                            echo_failure "looking for Microcode" "FAILED"
	                    noEm8300setup="true";
			fi
                fi
        else
                echo_warning "looking for em8300setup" "no em8300setup found, may be it's not needed"
                noEm8300setup="true";
        fi
	


        # *********** Do the devices exist? ********************
        for dev in /dev/em8300-0 /dev/em8300_mv-0 /dev/em8300_ma-0 /dev/em8300_sp-0; do
                if [ -e  $dev ]; then
                        echo_ok "detecting device $dev" "OK"
                else			    
                        echo_failure "detecting device $dev" "FAILED"
                fi
        done
	
	if [ -e /dev/em8300_ma-0 ]; then
		echo_ok "detecting device /dev/em8300_ma-0" "OK"
        else	
		# treatment for module versions which use ALSA
		rmmodules
		rmmodules
		modprobe bt865
		modprobe -q em8300 audio_driver=oss >/dev/null 2>/dev/null
		if [ -e /dev/em8300_ma-0 ]; then
		    echo_ok "detecting device /dev/em8300_ma-0" "OK"
		else
        	    echo_failure "detecting device /dev/em8300_ma-0" "FAILED"
		fi
	fi

        # ********** Can the modules be removed?  **********
        echo "trying to remove the modules..."
        sleep 2
        for module in em8300 adv717x bt865; do  
                if ! modprobe -q -r $module; then
                        echo_failure "removing modul $module" "FAILED"
                else
                        echo_ok "removing modul $module" "OK"
                fi
        done

        echo ""
        echo ""
        echo_ok "Press   ->  -> " "RETURN"
        read;
}

function setParamset ()
{
        function error ()
        {
                echo ""
                echo "Error: dxr3config could not determine the dxr3 module parameters."
                echo "This can have different reasons."
                echo "In most cases you can read the reason above.";
                echo ""
                if [ $auto = "true" ]; then
                        quit 6
                fi
        }
        if [ -f /proc/em8300/0 ]; then
                cat /proc/em8300/0 > $TMPPATH/dxr3info.txt
                cardRev=$(grep 'Card revision' $TMPPATH/dxr3info.txt | awk '{print $NF}')
                chipRev=$(grep 'Chip revision' $TMPPATH/dxr3info.txt | awk '{print $NF}')
                videoEncoder=$(grep 'Video encoder:' $TMPPATH/dxr3info.txt | awk '{print $3}')
                videoEncoder=$(grep 'Video encoder:' $TMPPATH/dxr3info.txt | awk '{print $3}')
                moduleVersion=$(grep 'em8300 module version' $TMPPATH/dxr3info.txt | awk '{print $NF}')
                rm $TMPPATH/dxr3info.txt
                dxr3sum=$cardRev$chipRev$videoEncoder
                case $dxr3sum in
                        12ADV7175)      paramSet=3;;
                        22ADV7175)      paramSet=3;;
                        22BT865)        paramSet=11;;
                        12ADV7170)      getEEpromInfo;
                                        case $eepromInfo in
                                                ${eepromOut[2]})        paramSet=2;;
                                                ${eepromOut[1]})        paramSet=3;;
                                                *)                      error;;
                                        esac;;

                        22ADV7170)      getEEpromInfo;
                                        case $eepromInfo in
                                                ${eepromOut[2]})        paramSet=3;;
                                                ${eepromOut[1]})        paramSet=2;;
                                                *)                      error;;
                                        esac;;
                        *)              getEEpromInfo;
                                        case $eepromInfo in
                                                ${eepromOut[2]})        paramSet=2;;
                                                ${eepromOut[1]})        paramSet=3;;
                                                *)                      error;;
                                        esac;;
                esac		
        else
                error
        fi
	
}

function getEEpromInfo ()
{
        if ! modprobe eeprom >/dev/null 2>/dev/null; then
                echo_failure "The module eeprom is not available" "FAILED"
        fi
        if ! test  -d /sys/devices/platform; then
                        echo_failure "Error: No sysfs available" "FAILED"
        else
                found=no
                for f in /sys/devices/platform/i2c-* ; do
                        if grep EM8300 $f/name >/dev/null 2>&1 ; then
                                for e in $f/*/eeprom ; do
                                        if test -f $e ; then
                                                found=yes
                                                eepromInfo=$(od -v -h $e | grep 0000100)
                                                eepromInfo=${eepromInfo//" "/""}
                                        fi
                                done
                        fi
                done
                if test "$found" != "yes" ; then
                        echo_failure "Error: No dxr3-EEprom found" "FAILED"
                fi
        fi
}

function rmmodules ()
{
        #stopMpeg
        for module in em8300 adv717x bt865; do
                if ! modprobe -q -r $module; then
                        msg "ERROR: The module $module could not be removed.\\n\\nIf this happens again, you should leave dxr3config and try it after a reboot."
                fi
        done
}

function loadModules ()
{
        if [ $paramSet -gt 9 ]; then 
                adapter=""
                redblue=""
        fi
        if [ $paramSet != "0" ]; then
                if ! modprobe ${advParam[$paramSet]} $adapter $redblue; then
                        msg "An error occured while loading the dxr3-modules...";
                        return
                fi
                if ! modprobe ${emParam[$paramSet]}; then
                        msg "An error occured while loading the dxr3-modules...";
                        return 
                fi
        else
                if ! modprobe bt865; then 
                        msg "An error occured while loading the dxr3-modules...";
                        return
                fi
                if ! modprobe adv717x; then
                        msg "An error occured while loading the dxr3-modules...";
                        return
                fi
                if ! modprobe em8300; then
                        msg "An error occured while loading the dxr3-modules...";
                        return
                fi
        fi
        if [ "$noEm8300setup" = "false" ]; then
                em8300setup -p -a -o >/dev/null 2>/dev/null;
        fi
}

function save ()
{
        if [ "$genScripts" = "true" ]; then
                makeScripts;
                msg "This files have been generated:\\n\\n$scriptsPath/load_dxr3\\n$scriptsPath/unload_dxr3";
        fi;
        if [ "$genModprobe" = "true" ]; then
                makeModprobe;
                if [ "$modify" = "true" ]; then
                        str="modified";
                else
                        str="generated";
                fi;
                msg "This file has been $str:\\n\\n$moduleFile\\n\\n";
        fi;
}

function msg ()
{
        if [ "$auto" = "false" ]; then
                dialog --backtitle "$title" --msgbox "$1" 0 0;
        else
                echo ${1//'\\n'/ };
        fi
}

function makeScripts ()
{
        echo "#!/bin/bash" > $scriptsPath/load_dxr3;
        echo "# This script was generated by dxr3config Version: $version" >> $scriptsPath/load_dxr3;
        echo "# You can use it to load the modules for your dxr3 card" >> $scriptsPath/load_dxr3;
        echo "# You are using parameter set $paramSet" >> $scriptsPath/load_dxr3; 
        echo "modprobe i2c-core" >> $scriptsPath/load_dxr3
        echo "modprobe i2c-algo-bit" >> $scriptsPath/load_dxr3
        echo "modprobe ${advParam[$paramSet]} $adapter $redblue" >> $scriptsPath/load_dxr3;
        echo "modprobe ${emParam[$paramSet]}" >> $scriptsPath/load_dxr3;
        chmod 775 $scriptsPath/load_dxr3;

        echo "#!/bin/sh" > $scriptsPath/unload_dxr3;
        echo "#This file was generated by dxr3config $version" >> $scriptsPath/unload_dxr3;
        echo "#You can use it to unload the modules for your dxr3 card" >> $scriptsPath/unload_dxr3;
        echo "" >> $scriptsPath/unload_dxr3;
        echo "#fuser -k /dev/em8300-0" >> $scriptsPath/unload_dxr3;
        echo "#fuser -k /dev/em8300_mv-0" >> $scriptsPath/unload_dxr3;
        echo "#fuser -k /dev/em8300_ma-0" >> $scriptsPath/unload_dxr3;
        echo "modprobe -r em8300" >> $scriptsPath/unload_dxr3;
        echo "modprobe -r adv717x" >> $scriptsPath/unload_dxr3;
        echo "#modprobe -r i2c-algo-bit" >> $scriptsPath/unload_dxr3;
        chmod 775 $scriptsPath/unload_dxr3;
}


function makeModprobe ()
{
                if [ $paramSet -gt 9 ]; then
                        chip="bt865"
                else
                        chip="adv717x"
                fi
                if [ $modify = "false" ]; then
                        # Attention: moduleFile is here a directory !
                        moduleFile=$modprobed
                        if [ ! -d $moduleFile ]; then
                                mkdir $moduleFile 
                        fi
                        # Attention: Now moduleFile is a file !
                        moduleFile="$moduleFile/em8300"
                        if [ -w $moduleFile ]; then
                                mv -f $moduleFile $(pwd)/em8300.old
                        fi
                else
                        if [ -w $moduleFile ]; then
                                cp $moduleFile $moduleFile.orig
                        fi
                fi
                if [ -w $moduleFile ]; then
                        sed -i '/^[[:blank:]]*#/!{/^.*\(adv717x\|bt865\|em8300\)/s/\(.*\)/#\1/}' $moduleFile
                fi
                echo "#configuration for adv717x bt865 em8300, generated by dxr3config $version" >> $moduleFile
                echo "#chip-parameterset: $paramSet" >> $moduleFile
                echo "alias char-major-121 em8300" >> $moduleFile
                echo "install em8300 /sbin/modprobe $chip && /sbin/modprobe --ignore-install em8300" >> $moduleFile
                echo "remove em8300 /sbin/modprobe -r --ignore-remove em8300 && /sbin/modprobe -r $chip" >> $moduleFile
                echo "options ${advParam[$paramSet]} $adapter $redblue" >> $moduleFile
                echo "options ${emParam[$paramSet]}"  >> $moduleFile
}

function menuParam ()
{
if      dialog --default-item $paramSuggestion --backtitle "$title" --menu "Option $paramSuggestion should fit for your dxr3-card." 0 0 0 \
        "1" "only for adv717x" \
        "2" "only for adv717x" \
        "3" "only for adv717x" \
        "4" "only for adv717x" \
        "10" "only for bt865"  \
        "11" "only for bt865"  \
        "12" "only for bt865"  \
        "13" "only for bt865"   2> $TMPPATH/dxr3config.tmp; then
        paramOption=$(cat $TMPPATH/dxr3config.tmp);
        if [ $paramOption != "0" ]; then
                paramSet=$paramOption;
        fi;
else
        paramOption=0
fi
}

function menuAdapter ()
{

if      dialog --backtitle "$title" --menu "Try one of these options:" 0 0 0 \
        "1" "For svideo-cables or the SigmaDesings adapter (default)" \
        "2" "For svideo to SCART or composite adapters (only composite output)" \
        "3" "For some svideo to composite adapters (only composite output)" \
        "4" "For some svideo to composite adapters (only composite output)" \
        "5" "For special YUV-adapters (Be carefull!)" 2> $TMPPATH/dxr3config.tmp; then
                adaptertmp=$(cat $TMPPATH/dxr3config.tmp)
                loop3="leave";
                if [ ! -z $adaptertmp ]; then
                        adapter=${adapterParam[$adaptertmp]};
                fi

else
        loop3="stay";
fi
}


function menuRedBlue ()
{
if      dialog --backtitle "$title" --menu "Try one of this options:" 0 0 0 \
        "2" "only for PAL (try this first)" \
        "3" "only for PAL (default for PAL)" \
        "4" "only for PAL" \
        "5" "only for pal" \
        "6" "only for NTSC" \
        "7" "only for NTSC (default for NTSC)" \
        "8" "only for NTSC" \
        "9" "only for NTSC" 2> $TMPPATH/dxr3config.tmp; then
                redbluetmp=$(cat $TMPPATH/dxr3config.tmp);
                loop3="leave";
                if [ ! -z "$redbluetmp" ]; then
                        redblue=${redblueParam[$redbluetmp]};
                fi
else
        loop3="stay";
fi
}

function genplayer ()
{
        echo "while [ 0 -eq 0 ]; do" > $TMPPATH/playM2V.sh
        echo "if [ -f $TMPPATH/playM2V.stop ]; then" >> $TMPPATH/playM2V.sh
        echo "rm $TMPPATH/playM2V.stop" >> $TMPPATH/playM2V.sh
        echo "exit" >> $TMPPATH/playM2V.sh
        echo "fi" >> $TMPPATH/playM2V.sh
        echo "cat $TMPPATH/tmp.m2v >/dev/em8300_mv-0 2>/dev/null" >> $TMPPATH/playM2V.sh
        echo "done" >> $TMPPATH/playM2V.sh
        chmod 775 $TMPPATH/playM2V.sh
}

function startMpeg ()
{       
        if [ -w $TMPPATH/playM2V.stop ]; then
                rm $TMPPATH/playM2V.stop
        fi
        if [ -e  /dev/em8300_mv-0 ]; then
                $TMPPATH//playM2V.sh >/dev/null 2>/dev/null &
        else
                msg  "The device /dev/em8300_mv-0 is not available.\\ndxr3config can not play the test image\\n\\n Try it again after a reboot."
                quit 1;
        fi
}

function stopMpeg ()
{
                touch $TMPPATH/playM2V.stop
                catID=""
                catID=$(ps ax | grep -v grep | grep "cat $TMPPATH/tmp.m2v" | awk '{print $1}')
                if [ -n "$catID" ]; then
                        kill -SIGKILL $catID >/dev/null 2>/dev/null;
                fi
                sleep 2
}


function showTestPicture ()
{
        dialog --backtitle "$title" --msgbox "Now the modules will be loaded and a test picture will be shown on your TV-screen...." 8 54
        dialog --backtitle "$title" --infobox "starting, please wait......." 0 0;
        loadModules
        sleep 2
        startMpeg
        sleep 2
        msg "Stop playing?"
        dialog --backtitle "$title" --infobox "stopping, please wait......." 0 0
        stopMpeg
        rmmodules
}


function menuTestResult ()
{
        dialog --backtitle "$title" --menu "Choose an option:" 0 0 0 \
        "BW" "The image was only/nearly Black&White (adapter settings)" \
        "RB" "RED and BLUE was inverted" \
        "P" "The colors looked very strange" \
        "EXIT" "Exit without saving" \
        "SAVE" "Save and exit" 2> $TMPPATH/dxr3config.tmp;
        testresult=$(cat $TMPPATH/dxr3config.tmp);
}

function menuTestResultbt865 ()
{
        dialog --backtitle "$title" --menu "Choose an option:" 0 0 0 \
        "P" "I want to try an other parameterset" \
        "EXIT" "Exit without saving" \
        "SAVE" "Save and exit" 2> $TMPPATH/dxr3config.tmp;
        testresult=$(cat $TMPPATH/dxr3config.tmp);
}

function genEmptyModprobe ()
{
        empty=$TMPPATH/emptyModprobe.conf
        if [ -d $TMPPATH ]; then
                echo "#empty" > $empty
        else
                msg "Error: dxr3config can not write to $TMPPATH"
                quit 7
        fi
}

function genM2V ()
{
        if test -f $M2VPATH/dxr3config.m2v ; then
                cat $M2VPATH/dxr3config.m2v > $TMPPATH/tmp.m2v;
                typeset -i i;
                i=1;
                while [ $i -le 500 ]; do
                        cat $M2VPATH/dxr3config.m2v >> $TMPPATH/tmp.m2v
                        i=$((i+1))
                done
        else
                echo_failure "Error: No dxr3config.m2v found in:" "$M2VPATH"
                echo ""
        fi
}

function main ()
{
if [ "$auto" = "true" ]; then
        echo ""
        echo "This is dxr3config $version (auto-mode)"
        echo ""
        loadModules;
        setParamset;
	manage_audio_driver;
        save;
        rmmodules;
        echo "Eprom Info:     $eepromInfo"
        echo "Card-Revision:  $cardRev"
        echo "Chip-Revision:  $chipRev"
        echo "Video-Encoder:  $videoEncoder"
        echo "Module-Version: $moduleVersion"
        echo ""
        echo "Loading dxr3-modules with paramset $paramSet:"
        echo ""
        echo "modprobe ${advParam[$paramSet]} $adapter $redblue"
        echo "modprobe ${emParam[$paramSet]}"
        echo ""
        loadModules
        quit 0;
else
        clear
        echo ""
        echo "This is dxr3config $version"
        echo ""
        setDistSettings
        genM2V &
        genplayer &
        preCheck
	manage_audio_driver
        paramSuggestion=$paramSet
        loop1="stay";
        while [ x$loop1 == x"stay" ]; do
                menuParam
                loop2="stay";
                while [ $loop2 != "leave"  ]; do
                        if [ $paramOption -gt 0 ]; then
                                showTestPicture
                        fi
                        loop3="stay";
                        while [ x$loop3 == x"stay" ]; do
                                loop3="leave";
                                if [ $paramOption -gt 9 ]; then
                                        menuTestResultbt865;
                                else
                                        menuTestResult;
                                fi
                                case $testresult in
                                        BW)     menuAdapter;;
                                        RB)     menuRedBlue;;
                                        P)      loop2="leave";
                                                loop1="stay";;
                                        EXIT)   loop2="leave";
                                                loop1="leave";;
                                        SAVE)   save;
                                                loop2="leave";
                                                loop1="leave";;
                                        *)      loop2="leave";
                                                loop1="leave";;
                                esac
                        done
                done
        done
        rmmodules;
        echo "Loading dxr3-modules with paramset: $paramSet"
        echo ""
        echo "modprobe ${advParam[$paramSet]} $adapter $redblue"
        echo "modprobe ${emParam[$paramSet]}"
        echo ""
        loadModules
        quit 0
fi
}

genEmptyModprobe
modprobe i2c-core
modprobe i2c-algo-bit
checkVDRrunning
checkRoot
main