#!/bin/bash
version=0.99rc1
# Copyright JOTENAKIS
# ce script est sous license GPL
# merci  tous les membres de OSA qui m'ont donn un coup de main et en particulier  zeb_  et  philou_a7 ;-)
# merci  jj Varv**** pour l'info lisant automatiquement le nom du DVD :)
# merci  Denis M. pour la correction du bug de dtermination des variables aspect,resX...  ;-).
# merci  Redo pour toutes ses modifs dans le code (cf changelog).
# Corrections de bugs et support de transcode: CREX
#==============================================
Png="png:z=0"
dvdsyntaxe="dvd://"
FOURCC="DX50"
deint="kerndeint"

# chemin vers les principales applis
mplayer=`which mplayer`
mencoder=`which mencoder`
tccat=`which tccat`
tcdecode=`which tcdecode`
tcscan=`which tcscan`
tcextract=`which tcextract`
transcode=`which transcode`
tcprobe=`which tcprobe`
tcdemux=`which tcdemux`

# fichiers de conf de tuxrip dplacs dans un dossier cach ~/.tuxrip/
[ ! -e $HOME/.tuxrip ] && mkdir $HOME/.tuxrip
fichierconf="$HOME/.tuxrip/tuxriprc"
fichierlng="$HOME/.tuxrip/tuxriplng"
[ -e $HOME/.tuxriprc ] && \rm -f $HOME/.tuxriprc 2>/dev/null
if [ -e $HOME/.tuxriplng ] && [ ! -e $fichierlng ] ; then
    \mv $HOME/.tuxriplng $fichierlng
fi

# Pour une sortie propre
trap 'echo "[1;0m" ; exit 0' 1 2 3
#==================================
# Definition de variables prealable
SCRIPT=$0
ShellPath=`dirname ${SCRIPT}`
Shell=`basename ${SCRIPT}`
if [ -e /usr/share/tuxrip ]; then
        SharePath=/usr/share/tuxrip
elif [ -e /usr/local/share/tuxrip ]; then
        SharePath=/usr/local/share/tuxrip
fi
# Ce bloc permet de resoudre les liens en chemin physique
if [ -L ${ShellPath}/${Shell} ]; then
        SCRIPT=`\ls -l ${ShellPath}/${Shell} | awk '{ print $NF }'`
        ShellPath=`dirname ${SCRIPT}`
        Shell=`basename ${SCRIPT}`
fi
# chargement du fichier de preset
if [ -f $HOME/.tuxrip/tuxrip_preset ]; then    # on cherche dans ~/.tuxrip/
	source $HOME/.tuxrip/tuxrip_preset
        echo "Using $HOME/.tuxrip/tuxrip_preset video settings file."
elif [ -f ${SharePath}/tuxrip_preset ]; then    # on cherche dans /usr/share/tuxrip/
	source ${SharePath}/tuxrip_preset
        echo "Using ${SharePath}/tuxrip_preset video settings file."
elif [ -f ${ShellPath}/tuxrip_preset ]; then  # on cherche dans ./
	source ${ShellPath}/tuxrip_preset
        echo "Using ${ShellPath}/tuxrip_preset video settings file."
else
	echo "tuxrip_preset file not found."
	exit
fi


#*****************************************************************************************************
#*****************************************************************************************************
#*****************************************************************************************************
#*****************************************************************************************************

#====================#
# Bloc des fonctions #
#====================#

#============================
# Initialisation des couleurs
function setPalette() {
        COLOROFF="\033[1;0m"    # standart color
        HEADCOLOR="\033[1;32m"  # green
        MAINCOLOR="\033[1;37m"  # white
        SUBCOLOR="\033[1;36m"   # blue
        TABLECOLOR="\033[1;31m" # red
        INPUTCOLOR="\033[1;35m" # lilac
	YELLOW="\033[1;33m"
}

#========================================
# On affiche le nom et la version du soft
# reglage "automatique" du cadre
function Banniere() {
	lgVersion=`echo $1 | awk '{print length()}'`
	lgVersion=`expr ${lgVersion} + 2`
	lineBorder="-------------------------------------------------"
	line=`echo ${lineBorder} | awk '{ print substr($1,1,'${lgVersion}')}'`
	echo -e "+${line}+"
	echo -e "| $1 |"	
	echo -e "+${line}+"
}

function localisation() {
	if [ -f $fichierlng ]; then
		lng=`cat $fichierlng`
	      	case $lng in
			"en") rep="ok" ;;
			"fr") rep="ok" ;;
			"sp") rep="ok" ;;
			   *) echo "Language not supported"
			      \rm $fichierlng
			      exit  ;;
		esac
		deflng="ok"
	else
		rep="notok"
		while [ "$rep" = "notok" ]; do
			echo "Language file not detected, which language do you want to use (en/fr/sp) ?"
			read lng
			case $lng in
				"en") rep="ok" ;;
				"fr") rep="ok" ;;
				"sp") rep="ok" ;;
				   *) echo "Language not supported" ;;
			esac
		done
		touch $fichierlng
		echo $lng > $fichierlng
		deflng="notok"
	fi

	#==========================================================
	# Les fichiers de lang sont separes dans un sous-repertoire
	# Chaque langue son fichier
	if [ -f ${SharePath}/lang/${lng}.lang ]; then    # on cherche dans /usr/share/tuxrip/lang/
		source ${SharePath}/lang/${lng}.lang
		echo "Using ${SharePath}/lang/${lng}.lang language file."
	elif [ -f ${ShellPath}/lang/${lng}.lang ]; then  # on cherche dans ./lang/
		source ${ShellPath}/lang/${lng}.lang
		echo "Using ${ShellPath}/lang/${lng}.lang language file."
	else
		echo "Language file ${lng}.lang not found."
		exit
	fi
}

function check_duration () {
        duree=`cat $projectRoot/tmp/infos.sound 2>/dev/null | grep "length" | awk -F "=" '{print $3}' | awk '{print $1}'`
        if [ "$duree" = "" ]; then
              title=`cat $projectRoot/tmp/log | grep scan | awk '{print $5}'`
              duree=`cat $projectRoot/tmp/infos.dvd.$title | grep sec | grep tcprobe | awk '{print $5}'`
        fi
        if [ "$duree" = "" ]; then
              timet=`cat $projectRoot/tmp/infos.dvd.$title | grep "time" | awk '{print $5}'`
              Ht=`echo $timet | cut -d: -f 1`
              Mt=`echo $timet | cut -d: -f 2`
              St=`echo $timet | cut -d: -f 3`
              Ht=${Ht:=0}
              Mt=${Mt:=0}
              St=${St:=0}
              duree=`bc <<EOF
                        scale=0
                        ( ( $Ht * 3600 ) + ( $Mt * 60 ) + $St ) / 1
EOF`
        fi
        if [ "$duree" = "" ]; then
              echo "ERROR (check_duration)"
              exit
        fi
}

# teste la prsence d'un dvd dans le lecteur $DEVICE
function testdvdin () {
        dvdok="notok"
        while [ "$dvdok" = "notok" ]; do
           testdvd=`$tcprobe -i $DEVICE 2>/dev/null`
           [ "$debug" = "OK" ] && $tcprobe -i $DEVICE
           if [ "$testdvd" = "" ]; then
              echo -e "${SUBCOLOR}$p131 $DEVICE $p132${MAINCOLOR}"
              read
           else
              dvdok="ok"
           fi
        done
}

# calcul la dure et la rapidit de traitement
function speed () {
   check_duration
   t2=`date +'%s'`
   nbhrs=`bc <<EOF
          scale=0
          ($t2 - $t1) / 3600
EOF`
   nbmin=`bc <<EOF
          scale=0
          ($t2 - $t1) / 60 - $nbhrs * 60
EOF`
   nbsec=`bc <<EOF
          scale=0
          ($t2 - $t1) - $nbmin * 60 - $nbhrs * 3600
EOF`
   vit_temp=`bc <<EOF
          scale=2
          $duree / ($t2 - $t1) * $fps
EOF`

}

# informations finales
function tuxripinfo () {
           echo -e "${TABLECOLOR}$p13${MAINCOLOR}"
           echo -e "${HEADCOLOR}"
           cat $projectRoot/tmp/riptime
           cat $projectRoot/tmp/audiotime
           cat $projectRoot/tmp/videotime
           cat $projectRoot/tmp/mixtime
           cat $projectRoot/tmp/ripspeed
           cat $projectRoot/tmp/audiospeed
           cat $projectRoot/tmp/videospeed
           cat $projectRoot/tmp/mixspeed
           echo -e "${HEADCOLOR}$p14${taillefilm}$p117"
           echo -e "${HEADCOLOR}$p15${filesize}$p117"
           echo -e "${MAINCOLOR}"
}

#*****************************************************************************************************
#*********************************  Copie du DVD dans $projectRoot ***********************************
#*****************************************************************************************************
function rip () {
         echo -e "${TABLECOLOR}$p166 ${MAINCOLOR}"
         free=`\df -P -T -m $RACINE | grep /dev | awk '{print $5}'`
         if [ $free -le 8000 ]; then # attention il n'y a pas bcp d'espace libre !
                echo
                echo "$free$p254 $RACINE$p255"
                isformat=""
                until [ "$isformat" != "" ]; do
                       echo -n -e "${SUBCOLOR}------->$p295"
                       echo -n -e "${INPUTCOLOR}> "
                       read verif
                       [ "$verif" = "N" ] && verif=n
                       [ "$verif" = "$p3" ] && verif=$p4
                       if [ "$verif" = "" ]; then
                             verif=n
                       fi
                       if [ "$lng" = "fr" ]; then
                             isformat=`echo $verif | grep "^[oOnN]$"`
                       elif [ "$lng" = "en" ]; then
                             isformat=`echo $verif | grep "^[yYnN]$"`
                       elif [ "$lng" = "sp" ]; then
                             isformat=`echo $verif | grep "^[sSnN]$"`
                       fi
                       if [ "$isformat" = "" ]; then
                             echo "$p124"
                       fi
                       echo -n -e "${MAINCOLOR}"
                       if [ "$verif" = "$p4" ]; then
                             echo > /dev/null
                       elif [ "$verif" = "n" ]; then
                             exit
                       fi
                done
         fi
         analyze_audio_type # ac3, pcm... ?
         testdvdin
         echo
         if [ "$fat32" = "OK" ]; then
                if [ "$modetest" = "OK" ]; then
                      echo -e "${HEADCOLOR}$p167${SUBCOLOR}${title}${HEADCOLOR} ($p168${SUBCOLOR}${full}${HEADCOLOR}) $p169"
                      echo -e "${SUBCOLOR}$projectRoot/vob/${projet}-*.vob${HEADCOLOR}...${MAINCOLOR}"
                else
                      echo -e "${HEADCOLOR}$p167${SUBCOLOR}${title}${HEADCOLOR} $p169"
                      echo -e "${SUBCOLOR}$projectRoot/vob/${projet}-*.vob${HEADCOLOR}...${MAINCOLOR}"
                fi
         else
                if [ "$modetest" = "OK" ]; then
                      echo -e "${HEADCOLOR}$p167${SUBCOLOR}${title}${HEADCOLOR} ($p168${SUBCOLOR}${full}${HEADCOLOR}) $p169"
                      echo -e "${SUBCOLOR}$projectRoot/vob/$projet.vob${HEADCOLOR}...${MAINCOLOR}"
                else
                      echo -e "${HEADCOLOR}$p167${SUBCOLOR}${title}${HEADCOLOR} $p169"
                      echo -e "${SUBCOLOR}$projectRoot/vob/$projet.vob${HEADCOLOR}...${MAINCOLOR}"
                fi
         fi
         t1=`date +'%s'`
         if [ "$fat32" = "OK" ]; then
                cd $projectRoot/vob
                nice -$nice $tccat -t dvd -T $title,$full,$angle -i $DEVICE 2>/dev/null | split -b 1024m - $projet
                [ -e $projectRoot/vob/${projet}aa ] && \mv $projectRoot/vob/${projet}aa $projectRoot/vob/${projet}-1.vob
                [ -e $projectRoot/vob/${projet}ab ] && \mv $projectRoot/vob/${projet}ab $projectRoot/vob/${projet}-2.vob
                [ -e $projectRoot/vob/${projet}ac ] && \mv $projectRoot/vob/${projet}ac $projectRoot/vob/${projet}-3.vob
                [ -e $projectRoot/vob/${projet}ad ] && \mv $projectRoot/vob/${projet}ad $projectRoot/vob/${projet}-4.vob
                [ -e $projectRoot/vob/${projet}ae ] && \mv $projectRoot/vob/${projet}ae $projectRoot/vob/${projet}-5.vob
                [ -e $projectRoot/vob/${projet}af ] && \mv $projectRoot/vob/${projet}af $projectRoot/vob/${projet}-6.vob
                [ -e $projectRoot/vob/${projet}ag ] && \mv $projectRoot/vob/${projet}ag $projectRoot/vob/${projet}-7.vob
                [ -e $projectRoot/vob/${projet}ah ] && \mv $projectRoot/vob/${projet}ah $projectRoot/vob/${projet}-8.vob
                [ -e $projectRoot/vob/${projet}ai ] && \mv $projectRoot/vob/${projet}ai $projectRoot/vob/${projet}-9.vob
         else
                dest="$projectRoot/vob/$projet.vob"
                if [ "$debug" = "OK" ]; then
                        nice -$nice $tccat -t dvd -T $title,$full,$angle -i $DEVICE > $dest
                else
                        nice -$nice $tccat -t dvd -T $title,$full,$angle -i $DEVICE 2>/dev/null > $dest
                fi
         fi
         analyze_audio_gain
}

#*****************************************************************************************************
#*********************************  dcoupage fichier final  *****************************************
#*****************************************************************************************************
function videofilecut () {
taillefilm=`bc <<EOF
   scale=6
   $(\ls -l $projectRoot/video/${projet}.$extvideo | awk '{print $5}') / 1024 / 1024
EOF`
case $filesize in
   1300 ) echo -e "${TABLECOLOR}$p12"
            echo -e "${MAINCOLOR}"
            if [ "$contain" = "ogm" ]; then
               ogmsplit $projectRoot/video/${projet}.$extvideo -s 650
            elif [ "$contain" = "avi" ]; then
               echo "$p389"
               echo
               #avisplit -i $projectRoot/video/${projet}.$extvideo -s 650
            elif [ "$contain" = "mkv" ]; then
               $merge --split 650m $projectRoot/video/${projet}.$extvideo -o $projectRoot/video/${projet}-cd'%1d'.$extvideo
            fi
            [ "$contain" = "ogm" ] && \mv $projectRoot/video/${projet}-*1.$extvideo $projectRoot/video/cd1/${projet}-cd1.$extvideo
            [ "$contain" = "ogm" ] && \mv $projectRoot/video/${projet}-*2.$extvideo $projectRoot/video/cd2/${projet}-cd2.$extvideo;;

   1400 ) echo -e "${TABLECOLOR}$p12"
             echo -e "${MAINCOLOR}"
             if [ "$contain" = "ogm" ]; then
                ogmsplit $projectRoot/video/${projet}.$extvideo -s 700
             elif [ "$contain" = "avi" ]; then
                echo "$p389"
                echo
                #avisplit -i $projectRoot/video/${projet}.$extvideo -s 700
             elif [ "$contain" = "mkv" ]; then
                $merge --split 700m $projectRoot/video/${projet}.$extvideo -o $projectRoot/video/${projet}-cd'%1d'.$extvideo
             fi
             [ "$contain" = "ogm" ] && \mv $projectRoot/video/${projet}-*1.$extvideo $projectRoot/video/cd1/${projet}-cd1.$extvideo
             [ "$contain" = "ogm" ] && \mv $projectRoot/video/${projet}-*2.$extvideo $projectRoot/video/cd2/${projet}-cd2.$extvideo ;;
esac
}

#*****************************************************************************************************
#*********************************  detection d'une extinction aprs encodage video ******************
#*****************************************************************************************************
function reprise() {
#on lit les variables ncssaires dans le log, le txriprc et le tuxripextinction
   RACINE=`cat ~/.tuxrip/shutdown | awk '{print $1}'`
   projet=`cat ~/.tuxrip/shutdown | awk '{print $2}'`
   projectRoot="$RACINE/$projet"
   decalinit=`cat ${fichierconf} | grep ^"3\." | awk '{print $2}'`
   VO=`cat ${fichierconf} | grep ^"8\." | awk '{print $2}'`
   AO=`cat ${fichierconf} | grep ^"9\." | awk '{print $2}'`
   filesize=`cat $projectRoot/tmp/log | grep bitrate | awk '{print $6}'`
   fps=`cat $projectRoot/tmp/log | grep scan | awk '{print $12}'`
   contain=`cat ${fichierconf} | grep ^"14\." | awk '{print $2}'`
   if [ "$contain" = "ogm" ]; then
      extvideo="ogm"
      extaudio="ogg"
      LISTE_APPLIS="ogmmerge ogmsplit"
      sortie="notok"
      for i in $LISTE_APPLIS;
      do
        which $i > /dev/null 2>&1
        if [ "$?" = "1" ]; then
           [ "$sortie" = "notok" ] && echo -e "${MAINCOLOR}$p282"
           echo -e "${HEADCOLOR} ${i}${MAINCOLOR}"
           sortie="ok"
        fi;
      done
      if [ "$sortie" = "ok" ]; then
         echo
         exit -1
      fi
      merge=`which ogmmerge`
   elif [ "$contain" = "mkv" ]; then
      extvideo="mkv"
      extaudio="ogg"
      LISTE_APPLIS="mkvmerge"
      sortie="notok"
      for i in $LISTE_APPLIS;
      do
        which $i > /dev/null 2>&1
        if [ "$?" = "1" ]; then
           [ "$sortie" = "notok" ] && echo -e "${MAINCOLOR}$p282"
           echo -e "${HEADCOLOR} ${i}${MAINCOLOR}"
           sortie="ok"
        fi;
      done
      if [ "$sortie" = "ok" ]; then
         echo
         exit -1
      fi
      merge=`which mkvmerge`
   elif [ "$contain" = "avi" ]; then
      extvideo="avi"
      extaudio="mp3"
      merge=`which avimerge`
   fi

   echo "$p16$projectRoot$p16bis"
   echo "$p17"
   echo "$p18"
   echo
   echo -e "${HEADCOLOR}$p19${MAINCOLOR}"
   cat $projectRoot/tmp/out.log | grep "Pos"
   cat $projectRoot/tmp/out.log | grep "CQ"
   echo
   etapedeb=7 # on finit le projet : affichage,mixage,dcoupage
#   [ "$contain" = "avi" ] && audiovideomix_avi || audiovideomix
   audiovideosync
   videofilecut
   tuxripinfo
   \rm ~/.tuxrip/shutdown
   exit
}

#*****************************************************************************************************
#*********************************  copie integrale du DVD sur HDD   *********************************
#*****************************************************************************************************
function clone() {
echo "$p17"
echo -n "$p271 "
if [ -r ${fichierconf} ] ; then
   RACINE=`cat ${fichierconf} | grep ^"1\." | awk '{print $2}'`
   echo "($RACINE/clone/)."
   DEVICE=`cat ${fichierconf} | grep ^"2\." | awk '{print $2}'`
   FS=`\df -P -T -m $RACINE | grep /dev | awk '{print $2}'`
   free=`\df -P -T -m $RACINE | grep /dev | awk '{print $5}'`
   if [ $free -le 9400 ]; then
      echo -e "${HEADCOLOR}$free$p254 $RACINE$p255${MAINCOLOR}"
      exit
   fi
   MNTDVD=`cat ${fichierconf} | grep ^"12\." | awk '{print $2}'`
   monte=`cat /etc/mtab | grep $MNTDVD`
   if [ "$monte" = "" ]; then
      mount $MNTDVD 2>$RACINE/errmount
      if [ "$RACINE/errmount" != "" ]; then
         monte=`cat /etc/mtab | grep $MNTDVD`
         if [ "$monte" = "" ]; then
            echo "$p276"
            exit
         fi
      fi
   fi
   [ -r $RACINE/errmount ] && \rm $RACINE/errmount
   copyvob=`which vobcopy 2>/dev/null`
   if [ "$copyvob" = "" ]; then
      echo "$p277"
   else
      nomclone=$( dd if=$DEVICE ibs=1 skip=32808 count=32 2>/dev/null | sed "s/\ //g" )
      [ "$nomclone" = "" ] && nomclone="DVD"
      echo
      if [ -d $RACINE/clone ]; then
         echo > /dev/null
      else
         mkdir $RACINE/clone
      fi
      vide="notok"
      until [ "$vide" = "OK" ]; do
            echo -n -e "${SUBCOLOR}-------> $p279 $nomclone ] ?${MAINCOLOR}"
            echo -n -e "${INPUTCOLOR}> "
            read projclone
            if [ "$projclone" = "" ]; then
               projclone=$nomclone
               echo "$p103 : $nomclone"
            fi
            if [ -d $RACINE/clone/$projclone ];then
               isformat=""
               while [ "$isformat" = "" ]; do
                     echo -n -e  "${SUBCOLOR}------->$p294"
                     echo -n -e "${INPUTCOLOR}> "
                     read verif
                     [ "$verif" = "N" ] && verif=n
                     [ "$verif" = "$p3" ] && verif=$p4
                     if [ "$verif" = "" ]; then
                        verif=n
                        echo "$p123"
                     fi
                     if [ "$lng" = "fr" ]; then
                          isformat=`echo $verif | grep "^[oOnN]$"`
                     elif [ "$lng" = "en" ]; then
                          isformat=`echo $verif | grep "^[yYnN]$"`
                     elif [ "$lng" = "sp" ]; then
                          isformat=`echo $verif | grep "^[sSnN]$"`
                     fi
                     if [ "$isformat" = "" ]; then
                        echo "$p124"
                     fi
                     echo -n -e "${MAINCOLOR}"
                     if [ "$verif" = "$p4" ]; then
                        \rm -rf $RACINE/clone/$projclone
                        vide="OK"
                     else
                        echo
                     fi
               done
            else
               echo -e "${MAINCOLOR}"
               vide="OK"
            fi
      done
      nice -$nice $copyvob -m -o $RACINE/clone -t $projclone
      monte=`cat /etc/mtab | grep $MNTDVD | grep supermount`
      [ "$monte" = "" ] && umount $MNTDVD
   fi
exit
else
   echo "$p101 --config"
   exit
fi
}

#*****************************************************************************************************
#*********************************  source sur HDD   *************************************************
#*****************************************************************************************************
function sourceprojet() {
         echo "$p284"
         RACINE=`cat ${fichierconf} | grep ^"1\." | awk '{print $2}'`
         [ -r $RACINE/clone/trouve ] && \rm $RACINE/clone/trouve
         if [ -d $RACINE/clone ]; then
                 yena="notok"
                 for directory in $(find $RACINE/clone -type d 2>/dev/null); do
                    if [ -d $directory/VIDEO_TS/ ]; then
                       yena="OK"
                       touch $RACINE/clone/trouve
                    fi
                 done
                 if [ "$yena" = "OK" ]; then
                       echo "$p287"
                       i=0
                       for directory in $(find $RACINE/clone -type d 2>/dev/null); do
                            if [ -d $directory/VIDEO_TS/ ]; then
                                   i=$(($i+1))
                                   echo -e "${HEADCOLOR}$i. $directory${MAINCOLOR}"
                                   echo "$i. $directory" >> $RACINE/clone/trouve
                            fi
                       done
                       nbclone=$i
                       i=$(($i+1))
                       echo "$i. $p286"
                       isnum=""
                       until [ "$isnum" != "" ]; do
                             echo -e -n "${SUBCOLOR}$p288 $i ] ?${INPUTCOLOR} >"
                             read rep
                             if [ "$rep" = "" ];then
                                   rep=$i
                                   echo -e -n "$p25 : "
                             fi
                             isnum=`echo $rep | grep "^[0-9][0-9]*$"`
                             if [ "$isnum" = "" ];then
                                   echo -e "${MAINCOLOR}$p291"
                             else
                                   if [ $rep -eq $i ];then
                                        echo "$p290"
                                        exit
                                   elif [ $rep -lt $i ] && [ $rep -ge 1 ]; then
                                        DEVICE=`cat $RACINE/clone/trouve | grep ^"$rep\." | awk '{print $2}'`
                                        echo $DEVICE
                                        \rm $RACINE/clone/trouve
                                        source="OK"
                                   else
                                        echo -e "${MAINCOLOR}$p292$i."
                                        isnum=""
                                   fi
                             fi
                       done
                       echo -e "${MAINCOLOR}"
                 else
                       echo "$p285 ($RACINE/clone)."
                       exit
                 fi
         else
                 echo "$p285 ($RACINE/clone)."
                 exit
         fi
}
#*****************************************************************************************************
#*****************************************************************************************************
#*****************************************************************************************************
#*****************************************************************************************************


#================#
# Bloc principal #
#================#
StartDate=`date +%Y%m%d`
StartTime=`date +%H:%M:%S`
# chargement des fichiers auxiliaires
if [ -f ${SharePath}/tuxrip_encode-$version ]; then    # on cherche dans /usr/share/tuxrip/
	source ${SharePath}/tuxrip_encode-$version
elif [ -f ${ShellPath}/tuxrip_encode-$version ]; then  # on cherche dans ./
	source ${ShellPath}/tuxrip_encode-$version
else
	echo "tuxrip_encode file not found."
	exit
fi
if [ -f ${SharePath}/tuxrip_mix-$version ]; then    # on cherche dans /usr/share/tuxrip/
	source ${SharePath}/tuxrip_mix-$version
elif [ -f ${ShellPath}/tuxrip_mix-$version ]; then  # on cherche dans ./
	source ${ShellPath}/tuxrip_mix-$version
else
	echo "tuxrip_mix file not found."
	exit
fi
if [ -f ${SharePath}/tuxrip_conf-$version ]; then    # on cherche dans /usr/share/tuxrip/
	source ${SharePath}/tuxrip_conf-$version
elif [ -f ${ShellPath}/tuxrip_conf-$version ]; then  # on cherche dans ./
	source ${ShellPath}/tuxrip_conf-$version
else
	echo "tuxrip_conf file not found."
	exit
fi
if [ -f ${SharePath}/tuxrip_analyze-$version ]; then    # on cherche dans /usr/share/tuxrip/
	source ${SharePath}/tuxrip_analyze-$version
elif [ -f ${ShellPath}/tuxrip_analyze-$version ]; then  # on cherche dans ./
	source ${ShellPath}/tuxrip_analyze-$version
else
	echo "tuxrip_analyze file not found."
	exit
fi
if [ -f ${SharePath}/tuxrip_project-$version ]; then    # on cherche dans /usr/share/tuxrip/
	source ${SharePath}/tuxrip_project-$version
elif [ -f ${ShellPath}/tuxrip_project-$version ]; then  # on cherche dans ./
	source ${ShellPath}/tuxrip_project-$version
else
	echo "tuxrip_project file not found."
	exit
fi
if [ -f ${SharePath}/tuxrip_videosettings-$version ]; then    # on cherche dans /usr/share/tuxrip/
	source ${SharePath}/tuxrip_videosettings-$version
elif [ -f ${ShellPath}/tuxrip_videosettings-$version ]; then  # on cherche dans ./
	source ${ShellPath}/tuxrip_videosettings-$version
else
	echo "tuxrip_videosettings file not found."
	exit
fi
# Les couleurs
setPalette
# La langue
localisation
# La banniere de bienvenue
echo
echo
echo -e -n "$TABLECOLOR"
Banniere "TUXRIP v${version}"
echo -e -n "$MAINCOLOR"
# Traitement en cas d'extinction pralable programme
if [ -r ~/.tuxrip/shutdown ]; then
   reprise
fi
# lecture de la ligne de commande
if [ -f ${SharePath}/tuxrip_cmdline-$version ]; then    # on cherche dans /usr/share/tuxrip/
	source ${SharePath}/tuxrip_cmdline-$version
elif [ -f ${ShellPath}/tuxrip_cmdline-$version ]; then  # on cherche dans ./
	source ${ShellPath}/tuxrip_cmdline-$version
else
	echo "tuxrip_cmdline file not found."
	exit
fi

# Tests des dpendances par philou_a7
read_config_file
LISTE_APPLIS="mplayer mencoder transcode tcprobe avimerge tccat tcextract tcdecode tcscan grep egrep awk sed bc expr $visu split dvdxchap"
sortie="notok"
for i in $LISTE_APPLIS;
do
 which $i > /dev/null 2>&1
 if [ "$?" = "1" ]; then
  [ "$sortie" = "notok" ] && echo -e "${MAINCOLOR}$p282"
  echo -e "${HEADCOLOR} ${i}${MAINCOLOR}"
  sortie="ok"
 fi;
done
if [ "$sortie" = "ok" ]; then
   echo
   exit -1
fi

# DEBUT : CREATION DU PROJET
if [ "$resume" != "OK" ]; then
      testdvdin
fi
test_project
if [ "$resume" = "OK" ]; then # on redmarre
      restart_project
else # on cre un nouveau
      create_new_project
fi
cd $projectRoot

# ETAPE 1 : ANALYSE DU DVD
if [ $etapedeb -le 1 ]; then
      dvd_analyze
fi
if [ "$sub" = "OK" ]; then
      extract_sub
fi

# ETAPE 2 : detection automatique du dcoupage des bandes noires (CROP).
if [ $etapedeb -le 2 ]; then
      echo -e "${TABLECOLOR}$p175${MAINCOLOR}"
      autocrop
      echo
      echo "cropping --> $crop $haut $larg"  >> $projectRoot/tmp/log
fi

# ETAPE 3 : Copie des vobs et recherche des gains audios (RIP)
if [ $etapedeb -le 3 ]; then
      rip
      speed
      vitrip=$vit_temp
      echo "$p258 : ${nbhrs}hrs ${nbmin}min ${nbsec}sec" | tee $projectRoot/tmp/riptime
      echo "$p259 : $vitrip fps" | tee $projectRoot/tmp/ripspeed
      echo
      echo "ripping dvd" >> $projectRoot/tmp/log
      if [ "$source" != "OK" ]; then
          echo "$p374"
          echo
      fi
fi

# ETAPE 4 : TRAITEMENT AUDIO
if [ $etapedeb -le 4 ]; then
      echo -e "${TABLECOLOR}$p170${MAINCOLOR}"
      if [ "$ac3" = "OK" ]; then
            extaudio="ac3"
            extract_ac3
      else
            \rm -f $projectRoot/tmp/keep_ac3 2>/dev/null
            if [ "$multiaudio" != "OK" ];then
                  encode_audio_onetrack
            else
                  if [ "$contain" = "avi" ]; then
                      encode_audio_multi-track_mp3
                  else
                      encode_audio_multi-track
                  fi
            fi
      fi
      speed
      vitencaudio=$vit_temp
      echo "$p257 : ${nbhrs}hrs ${nbmin}min ${nbsec}sec" | tee $projectRoot/tmp/audiotime
      echo "$p260 : $vitencaudio fps" | tee $projectRoot/tmp/audiospeed
      if [ "$multiaudio" != "OK" ];then
         echo "encodage audio --> $vorbisquality" >> $projectRoot/tmp/log
      else
         echo "encodage audio --> multi" >> $projectRoot/tmp/log
      fi
      echo
fi

# ETAPE 5 : determination de la resolution.
if [ $etapedeb -le 5 ]; then
      echo -e "${TABLECOLOR}$p185${HEADCOLOR}"
      autosize
      echo "taille vise, rsolution, bitrate --> $filesize $scale $bitvideo" >> $projectRoot/tmp/log
fi

# ETAPE 6 : TRAITEMENT VIDEO
if [ $etapedeb -le 6 ]; then
      echo -e "${TABLECOLOR}$p218${MAINCOLOR}"
      codevideo
      speed
      vitencvideo=$vit_temp
      echo
      echo "$p256 : ${nbhrs}hrs ${nbmin}min ${nbsec}sec" | tee $projectRoot/tmp/videotime
      echo "$p261 : $vitencvideo fps" | tee $projectRoot/tmp/videospeed
      echo "encodage video" >> $projectRoot/tmp/log
      if [ "$extinction" = "OK" ]; then
            echo
            echo "$p224"
            sleep 10
            touch ~/.tuxrip/shutdown
            echo $RACINE $projet >> ~/.tuxrip/shutdown # creation du fichier extinction
            grep -E "Mandrake|Mandriva" /etc/redhat-release &>/dev/null && halt || sudo /sbin/shutdown -h now
      fi
fi

# ETAPE 7 : mixage A/V
if [ $etapedeb -le 7 ]; then
      audiovideosync
      speed
      vitsynchro=$vit_temp
      [ "$contain" = "avi" ] && \rm $projectRoot/video/${projet}.$extvideo.nosync
      echo -n -e "${MAINCOLOR}"
      echo "$p262 : ${nbhrs}hrs ${nbmin}min ${nbsec}sec" > $projectRoot/tmp/mixtime
      echo "$p263 : $vitsynchro fps" > $projectRoot/tmp/mixspeed
      echo "mixage A/V -->  $decal" >> $projectRoot/tmp/log
fi

# FIN : dcoupe, info
videofilecut
tuxripinfo

echo -e "${MAINCOLOR}"
EndDate=`date +%Y%m%d`
EndTime=`date +%H:%M:%S`

echo "Programme lanc le ${StartDate}  ${StartTime}."
echo "Programme termin le ${EndDate}  ${EndTime}."
