#!/bin/bash

source /etc/cdcontrolrc

# Faz algumas checagens de status e recursos do sistema
#

if [ ! -x ${LOG_DIR}/tec ]; then mkdir -p ${LOG_DIR}/tec;fi
if [ ! -x ${TMP_DIR} ];     then mkdir -p ${TMP_DIR};    fi
if [ ! -x ${CFG_DIR} ];     then mkdir -p ${CFG_DIR};    fi

if [ $(echo \(${SYS_MEM}-\(${CACHE}*${WRITTERS}\)\)-4|bc) -lt 0 ];then
 echo "The maximum cache size for all writters is bigger than the amount"
 echo "of system memory. Please fix the problem in the configuration file"
 echo "and run this utility again."
 exit 1
fi

# O resultado da conta abaixo  a memria disponvel no sistema - 
# a memria livre de seguranda requerida por aquela velocidade de 
# gravao. A segunda expresso deve ser sempre maior ou igual a 
# primeira
if [ $(echo \(${SYS_MEM}-\(${CACHE}*${WRITTERS}\)\)-4|bc) -lt \
     $(echo 6*\(${W_SPEED}/4\)|bc) ];then
 echo "The resources specified in the configuration file are greather than"
 echo "the allowed by your system, because of it CDcontrol stoped."
 echo "Possible solutions are que decreasing of the write cache for the writters"
 echo "or adding more RAM memory to the system. Check your system resources."
 exit 1
fi

echo "RAM Memory  .........: ${SYS_MEM}"
echo "Writters ............: ${WRITTERS}"
echo "Recording Speed .....: ${W_SPEED}"
echo "Cache Memory used ..: $[${CACHE}*${WRITTERS}] (${CACHE}MB por ${WRITTERS} unidades)"


function selwritters {
 local L_WRITTER L_WRITTER_S L_TOTAL L_TEMPO L_TEMPOE L_TEMPOR L_IMGSIZE L_SEG
 while [ ${C_TOTAL} -gt 0 ];do
   C_TOTAL=`cat ${TMP_DIR}/.c_total.temp`
   L_TOTAL=${C_TOTAL}
   for L_WRITTER in `seq 1 ${WRITTERS}`;do
    L_WRITTER_S=$(echo `eval echo "\$\WRITTER"${L_WRITTER}""`)
    if [ ! -z `eval echo ${L_WRITTER_S}` ];then
     if cat ${CFG_DIR}/Recorder${L_WRITTER}.cfg|grep 'ENABLED=1' >/dev/null;then
      if [ ${L_TOTAL} -gt 0 ];then
       writtercontrol "$1" ${L_WRITTER} ${L_WRITTER_S} &
       ps ax --sort=ppid|grep cdrecord|grep -v 'grep cdrecord' | \
       tail -n 1|awk '{print $1}' >${TMP_DIR}/recorder${L_WRITTER}-busy
       let L_TOTAL=L_TOTAL-1
      fi
     fi
    fi
   done

   # Cria variveis para clculo do tempo de gravao
    # Verifica se ser feita uma gravao de audio ou dados e calcula o 
    # tamanho da imagem adequadamente. 
    if [ "${IMG_TYPE}" = "A" ];then
      L_IMGSIZE=$(du -h `echo "$1"|sed -e s/'\/track_\*\.wav'//` | \
                  awk '{print $1}'| sed -e s/'M$'//)
     elif [ "${IMG_TYPE}" = "D" ];then
      L_IMGSIZE=`du -h $1 | awk '{print $1}' | sed -e s/'M$'//`
    fi
    L_TEMPO=$(echo $[(${L_IMGSIZE}/(8*${W_SPEED}))*60])
    L_TEMPOE=$(echo `echo "${L_IMGSIZE}/(8*${W_SPEED})" | bc -l | \
             sed -e s/'.*\.'/"0."/ | cut -b 1-4`*60 | bc | sed -e s/'\..*'//)
    let L_TEMPO=L_TEMPO+L_TEMPOE-10
    L_SEG=0

    sleep 10; clear
    L_TEMPOR=$[(${L_TEMPO}-${L_SEG})/60]
    echo -en "\033[1;37mWritting, remaining time: ${L_TEMPOR} min, \033[0m"

   # Somente permite uma nova gravao caso nenhuma gravao esteja 
   # sendo feita atualmente. 
   while ls ${TMP_DIR}|grep 'recorder'|grep 'busy' >/dev/null;do 
    sleep 6
    if [ ${L_SEG} -lt ${L_TEMPO} ];then let L_SEG=L_SEG+6;fi
    if [ ${L_TEMPOR} -gt $[(${L_TEMPO}-${L_SEG})/60] ];then
     let L_TEMPOR=L_TEMPOR-1
     if [ ${L_TEMPOR} -gt 1 ];then
      echo -en "\033[1;37m${L_TEMPOR}, \033[0m"
     else
      echo -en "\033[1;37mless than 1 minute.\033[0m"
     fi
    fi 
   done

   echo;echo -e "\033[1;36m* Press ENTER to continue...\033[0m";read
   C_TOTAL=`cat ${TMP_DIR}/.c_total.temp`
   if [ ${C_TOTAL} -gt 0 ];then
    dialog  --backtitle "CDcontrol v${CDC_VERSION}" \
        --title "Write the rest of copies" \
        --yesno "There are ${C_TOTAL} copies to be done, press <Enter> when\n\
you be ready to continue. Press <Esc> ou select 'NO' to cancel. :" 7 64
    case $? in
     1)
      return
      ;;
     255)
      return
      ;;
    esac
   fi 
 done
}


# Dever ser executada na inicializao do programa
function checkstatus {
 local L_WRITTER L_WRITTER_S
 for L_WRITTER in `seq 1 ${WRITTERS}`;do
  L_WRITTER_S=$(echo `eval echo "\$\WRITTER"${L_WRITTER}""`)
  # Remove lockfiles anteriores, antes de iniciar a gravao
  if [ -f ${TMP_DIR}/recorder${L_WRITTER}-busy ];then
   echo "Removendo lock file da unidade ${L_WRITTER}..."
   rm -f ${TMP_DIR}/recorder${L_WRITTER}-busy
  fi
  # Apenas mostra a mensagem que a unidade ser desabilitada uma nica vez, a 
  # verdadeira desabilitao  feita pela funo selwritters
  if [ -z `eval echo ${L_WRITTER_S}` ];then
   echo "Configuration for writter ${L_WRITTER} not found, writter disabled."
  else
   # Cria o arquivo da unidade habilitada caso no existir
   if [ ! -f ${CFG_DIR}/Recorder${L_WRITTER}.cfg ];then
    echo "Creating a configuration file to writter ${L_WRITTER}..."
    echo "ENABLED=1" >${CFG_DIR}/Recorder${L_WRITTER}.cfg
    echo "ERRORS=2" >>${CFG_DIR}/Recorder${L_WRITTER}.cfg
    echo "OBS=" >>${CFG_DIR}/Recorder${L_WRITTER}.cfg
   fi
  fi
  rm -f ${TMP_DIR}/.Gravados-*.lock ${TMP_DIR}/.Falhas-*.lock
 done
}


# Verifica as dependncias do programa
function check_depends {
 local L_EXIT
 L_EXIT=0
 if ! which which &>/dev/null;then
  echo "The which program cound't be found or is out of currently path"
  exit 1
 fi
 echo "Checking dependencies... "
 if ! which awk &>/dev/null;then echo "Could not found the awk program";L_EXIT=1;fi
 if ! which bc &>/dev/null;then echo "Could not found the bc program";L_EXIT=1;fi
 if ! which cdda2wav &>/dev/null;then echo "Could not found the cdda2wav program";L_EXIT=1;fi
 if ! which cdrecord &>/dev/null;then echo "Could not found the cdrecord program";L_EXIT=1;fi
 if ! which cut &>/dev/null;then echo "Could not found the cut program";L_EXIT=1;fi
 if ! which dc &>/dev/null;then echo "Could not found the dc program";L_EXIT=1;fi
 if ! which df &>/dev/null;then echo "Could not found the df program";L_EXIT=1;fi
 if ! which dialog &>/dev/null;then echo "Could not found the dialog program";L_EXIT=1;fi
 if ! which grep &>/dev/null;then echo "Could not found the grep program";L_EXIT=1;fi
 if ! which lockfile &>/dev/null;then echo "Could not found the lockfile program";L_EXIT=1;fi
 if ! which ls &>/dev/null;then echo "Could not found the ls program";L_EXIT=1;fi
 if ! which ps &>/dev/null;then echo "Could not found the ps program";L_EXIT=1;fi 
 if ! which sed &>/dev/null;then echo "Could not found the sed program";L_EXIT=1;fi
 if ! which seq &>/dev/null;then echo "Could not found the seq program";L_EXIT=1;fi 
 if ! which sleep &>/dev/null;then echo "Could not found the sleep program";L_EXIT=1;fi
 if ! which tail &>/dev/null;then echo "Could not found the tail program";L_EXIT=1;fi
 if ! which touch &>/dev/null;then echo "Could not found the touch program";L_EXIT=1;fi
 if ! which uname &>/dev/null;then echo "Could not found the uname program";L_EXIT=1;fi 
 if ! echo ${SHELL}|grep -i 'bash' >/dev/null;then 
      echo "Shell Bash is requested";L_EXIT=1;fi

 # Sai caso alguma dependncia no seja encontrada
 if [ ${L_EXIT} != 0 ];then 
  exit 1
 else
  echo "All dependencies are OK, you can comment the 'check_depends' line"
  echo "at the end of this file do speed up the program start"
  sleep 4
 fi
}


# Funo de Inicio (colocada aqui para chamar a funo 'selwritters')
function inicio {
 local L_MAT_NAME L_TMPFILE L_RETVAL
 if [ "${IMG_TYPE}" = "A" ];then
  ls -F ${IMG_DIR}|grep '/' >/dev/null
 elif [ "${IMG_TYPE}" = "D" ];then
  ls -F ${IMG_DIR}|grep -v '/' >/dev/null
 fi
 if [ $? != 0 ];then
  echo "No one CD image was found, use the 'cd-memoria' utility to create one."
  exit 1
 fi

 # Cria o arquivo temporrio que ser usado para armazenar o valor de retorno
 # dos menus
 L_TMPFILE=`mktemp /tmp/fileXXXXXX`

 #------------------[ Inicio do menu de seleo de Imagem ]--------------------------
if [ "${IMG_TYPE}" = "A" ];then
 dialog  --backtitle "CDcontrol v${CDC_VERSION}" --clear \
         --title "Select a CD image to write" \
         --menu "Use the arrow keys and press <Enter>\n\
Press <Esc> or select 'Cancel' to exit:" 20 60 10 \
 `ls -F ${IMG_DIR} | grep '/' | sed -e s/"^"/"\""/ | \
  sed -e s/"\/$"/'\" \"\" \\ '/` 2>${L_TMPFILE}
elif [ "${IMG_TYPE}" = "D" ];then
 dialog  --backtitle "CDcontrol v${CDC_VERSION}" --clear \
         --title "Select a CD image to write" \
         --menu "Use the arrow keys and press <Enter>\n\
Press <Esc> or select 'Cancel' to exit:" 20 60 10 \
 `ls -F ${IMG_DIR} | grep -v '/' | sed -e s/"^"/"\""/ | \
  sed -e s/"\.iso$"/'\.iso\" \"\" \\ '/` 2>${L_TMPFILE}
fi

 L_RETVAL=$?
 L_MAT_NAME=`cat ${L_TMPFILE}`

 case ${L_RETVAL} in
   1)
     echo "Canceled by user."
     rm -f ${L_TMPFILE}
     exit 1
     ;;
   255)
     echo "Canceled by user."
     rm -f ${L_TMPFILE}
     exit 1
     ;;
 esac
 #Retira as "aspas" da seleo
 L_MAT_NAME=`echo ${L_MAT_NAME}|sed -e s/"\""//g`
 #--------------------------------------------------------------------------

# Seleciona o nmero de cpias
dialog  --backtitle "CDcontrol v${CDC_VERSION}" --clear --title "Number of copies" \
        --inputbox "Type the wanted number of copies of the CD image\n\
'${L_MAT_NAME}' and press <Enter>\n\
to start the writing. Press <Esc>, select 'Cancel' or\n\
press <Enter> without typing a value to exit." 10 60 2>${L_TMPFILE}
L_RETVAL=$?
C_TOTAL=`cat ${L_TMPFILE}`

case ${L_RETVAL} in
  0)
   if [ -z ${C_TOTAL} ];then
    echo "No one typed value"
    rm -f ${L_TMPFILE}
    exit 1
   fi
   echo ${C_TOTAL} >${TMP_DIR}/.c_total.temp
   if [ "${IMG_TYPE}" = "A" ];then
    selwritters "${IMG_DIR}/${L_MAT_NAME}/track_*.wav"
   elif [ "${IMG_TYPE}" = "D" ];then
    selwritters "${IMG_DIR}/${L_MAT_NAME}"
   fi
   ;;
  1)
   echo "Canceled by user."
   rm -f ${L_TMPFILE}
   exit 1
   ;;
  255)
   echo "Canceled by user."
   rm -f ${L_TMPFILE}
   exit 1
   ;;
esac
rm -f ${L_TMPFILE}

exit 0
}


# Verifica se tudo est correto para gravar e inicia o programa
check_depends
checkstatus
inicio

