#!/bin/sh

# ckdls - A Download Directory Processor
# Runs par & par-cmdline to repair, unzip and unRAR all your file downloadings.
# 
#
#
# Automatically creates par-report.txt files for use by the easyleech utils 
# (not being released yet). Other addon's may also be able to make use
# of the par-report.txt files. 
#
#
# The part where it tries to turn MPG files into VCD or
# SVCD CD Images is not finished yet. 
#
#
#

#
# Configuration stuff & header stuff
# (Not everything is completely implimented yet (7-15-2003)
#
# This is really really really developmental stuff, but it seems to work.
# I'm sure there are still a few bugs here and there. 
#
#
#


# configuration options. Change the values here
# to modify the scripts behavior. 

#
# Empty value is false, anything else is true.
# Boolean value is determained by string functions.
#
VERSION="0.05-alpha"
DEBUG="1"
VERBOSE="1"
QUIET=""
NOUNRAR=""
NOREPAIR=""
NOTEST=""
NEEDHELP=""
SIMULATE=""
RECURSIVE=""
CONTINUOUS=""
CONTINUOUS_DELAY="7200"
DO_NOT_DELETE="1"
DO_NOT_UNARCHIVE=""
DO_NOT_REPAIR=""
DIR_PARAM=""
DEFAULT_DIR="${HOME}/downloads"
FINISHED_DIR="${HOME}/finished"
FINDCMD=""

# Currently set to not delete. This because I have noticed times when it
# will delete the archive files, even though the unarchiving process
# was not successful. I haven't tracked that bug down yet.


#
# Process command line arguments.
#
for PARAM in $@
do
case "$PARAM" in 
   "-h" | "-H" | "-help" | "-HELP" | "--help" | "--HELP" | "-?") NEEDHELP=1 ;;
   "-q" | "-quiet" | "-Q" | "-QUIET" | "--quiet" | "--QUIET" ) QUIET=1
                                       VERBOSE="";;
   "-v" | "-verbose" | "-V" | "-VERBOSE" | "--verbose" | "--VERBOSE" ) 
                                       if [ ! -n "$QUIET" ] ; then
                                       VERBOSE=1
                                       fi;;
   "--debug" | "-debug" ) DEBUG="1" ; VERBOSE="1" ;;
    "-r" | "-R" | "--recursive" | "-recursive" | "--RECURSIVE" | "-RECURSIVE" ) RECURSIVE="1";;
   "-d" | "-d" ) LASTWASD=1;;
   "-n" | "-N" ) DO_NOT_DELETE=1;;
   "--continuous" | "--CONTINUOUS" | "-continuous" | "-CONTINUOUS" ) CONTINUOUS="1";;
   "--simulate" | "--SIMULATE" | "-simulate" | "-SIMULATE" ) SIMULATE="1";;
   "--norepair" | "--NOREPAIR" | "-norepair" | "-NOREPAIR" ) NOREPAIR="1";;
   "--notest" | "--NOTEST" | "-notest" | "-NOTEST" ) NOTEST="1";;
   "--nounrar" | "--NOUNRAR" | "-nounrar" | "-NOUNRAR" ) NOUNRAR="1";;
   *) if [ -n "$LASTWASD" ] ; then
            CONTINUOUS_DELAY="${PARAM}"
            CONTINUOUS=1
            LASTWASD=""
      fi
      if [ -n "${DIR_PARAM}" ] ; then
         echo unknown and/or too many  parameters specified.
	 echo Turning on debugging, displaying help and exiting. read up!
	 echo
	 NEEDHELP=1
         DEBUG=1
      else
	 DIR_PARAM="${PARAM}"
      fi
esac

done


if [ -n "${DEBUG}" ] ; then
     	echo DEBUG=$DEBUG
	echo VERBOSE=$VERBOSE
	echo QUIET=$QUIET
	echo NEEDHELP=$NEEDHELP
	echo SIMULATE=$SIMULATE
	echo RECURSIVE=$RECURSIVE
	echo CONTINUOUS=$CONTINUOUS
	echo CONTINUOUS_DELAY=$CONTINUOUS_DELAY
	echo DO_NOT_DELETE=$DO_NOT_DELETE
	echo DO_NOT_UNARCHIVE=$DO_NOT_UNARCHIVE
	echo DO_NOT_REPAIR=$DO_NOT_REPAIR
	echo DIR_PARAM=$DIR_PARAM
	echo DEFAULT_DIR=$DEFAULT_DIR
	echo NOREPAIR=$NOREPAIR
fi

if [ -n "${NEEDHELP}" ] ; then
        echo "ckdls ${VERSION} - The Usenet Download Checker"
        echo "Repairs and unarchives usenet file attachment sets"
	echo 
	echo "   ckdls <options> [download directory]"
        echo           
	echo "   -? -h --help   Displays this screen and exits"
 	echo "   --debug        Turns on debuging output (implies verbose)"
        echo "   --norepair     Turns off the PAR-parchive repair functionality"
        echo "   --notest       Turns off the archive pre-test (sometime faster)." 
        echo "   --nounrar      Turns off the unrar functionality. "
	echo "   --verbose -v   Turns on extra output "
        echo "   --quiet -q     Turns off all script output"
        echo "   --continuous   Continously process download directory"
 	echo "   -d [###]       Delay between continue runs, in seconds"
	echo "                  (implies continuous runs)"
	echo "   -r             Recursively scan subdirectories "
	echo "   -n             Do not delete the tobedeleted directory"
	echo
        echo "           more features coming soon"
	echo
	exit 1
fi





#
# If no parameter was specified...
#
if [ ! -n "$DIR_PARAM" ] ; then
        DIR_PARAM="${DEFAULT_DIR}"
	echo Directory not specified on command line
	echo Processing the default directory: ${DIR_PARAM}
fi



#
# The Find command has issues.
# Sometimes there are problems with weird characters, spaces, ect...
# 

if [ -n "${RECURSIVE}" ] ; then
	FINDCMD="find ${DIR_PARAM} -type d -maxdepth 3"
    else
        FINDCMD="find ${DIR_PARAM} -type d -maxdepth 0"
fi


STARTDIR="`pwd`"


if [ -n "$DEBUG" ] ; then
     	echo Debug - Finished processing command line parameters
fi






for each in `${FINDCMD} | tr ' ' '?'|grep -v tobedeleted` 
do 
    echo Processing ${each}
    MOVEDNOHUP=""
    echo ----- Changing To Directory: ${each}
    cd ${each}
    echo ----- Processing Directory: `pwd`

    # The cd command is acting goofy right here, and I don't know why.
    # The "cd ${each}" does not work, but with the pwd command in it, it does.


     

    #
    # If you download file fills from easynews (maybe by adding them manually to
    # an easynews ZIP manager queue, or by using the ckdls/easyleech utils)
    # then the ZIP file will need to be decompressed before all the new par, rar,
    # and zip parts will be available to finish recovery.
    #

    if [ -n "${DEBUG}" ] ; then
       echo looking for easynews zip files - find command: find . -name [1-6]-\*.[Zz][Ii][Pp] -maxdepth 1
       find . -name [1-6]-\*.[Zz][Ii][Pp] -maxdepth 1       
    fi 



    # let's try to unzip any easynews queues to the current directory.
    for ZIPFILE in `find . -name [1-6]-\*.[Zz][Ii][Pp] -maxdepth 1`
    do 

      


       ZIPBASE=`echo "${ZIPFILE}" |sed s/.[Zz][Ii][Pp]$//`
       if [ -n "${DEBUG}" ] ; then
	  echo Processing .zip: ZIPFILE= ${ZIPFILE} - ZIPBASE=${ZIPBASE}
       fi   
       unzip -o "${ZIPFILE}" -d . 
       if [ $? -eq 0 ] ; then
          if [ ! -d tobedeleted ] ; then 
             mkdir tobedeleted
          fi


          if [ -n "${DEBUG}" ] ; then
	     echo Moving ${ZIPFILE} to tobedeleted
          fi   


          mv "${ZIPFILE}" tobedeleted 
       fi
    done




    if [ -n "${DEBUG}" ] ; then
       echo running fixbad for automated rar-recovery
    fi   

    fixbad

    if [ -f ./par-report.txt ] ; then
       mv ./par-report.txt ./par-report.old
    fi


    #
    # Move any nohup.out files out of the way for now.
    #
    if [ -f ./nohup.out ] ; then
        mv nohup.out nohup.out.other
        MOVEDNOHUP=1
    fi


if [ ! -n "${NOREPAIR}" ] ; then 
    #
    # Start the .PAR and .PAR2 repair processes
    #
    rm -f nohup.out

    nohup par m -f -m *.[Pp][Aa0-9][Rr0-9] &
    PARPID=$!
   
    nohup par2repair  *.[Pp][Aa][Rr][2] &
    PAR2PID=$!

    sleep 1


    # We should have a nohup.out file, which we rename par-report.txt
    if [ -f ./nohup.out ] ; then
       mv nohup.out par-report.txt
    fi


    #
    # If we moved the nohup file before, put it back, something else might
    # need it
    #
    if [ -n "$MOVEDNOHUP" ] ; then
       mv nohup.out.other nohup.out
    fi

    # Show the par-report (as it's being generated) to the user
    # Run until the PARPID process ends, and all background processes.
    tail --pid=${PARPID} -f par-report.txt
    tail --pid=${PAR2PID} -f par-report.txt
    wait


    # rename the files to remove !'s and other special/goofy characters
    # that a dumb person choose to use in the filenames, incase the par restore
    # put it back. Don't the posters know better??? This fixes an
    # obscure problem that rarely occurs. Most know better....
    rename 'y/\!/./' *
    rename 'y/\(/./' *
    rename 'y/\)/./' *
    rename 'y/ /./' *
    rename "y/\'/./" *
fi

    for ZIPFILE in `find . -maxdepth 1 -type f -iregex .*\.zip$  -printf "%p\n" |tr "\ " "\?"`
    do 

      ZIPBASE=`echo ${ZIPFILE} |sed s/.[Zz][Ii][Pp]$// |tr ' ' '_'`
      if [ -n "${DEBUG}" ] ; then
          find . -maxdepth 1 -type f -iregex .*\.zip$  -printf "%p\n" |tr "\ " "\?"
          echo ZIPBASE=$ZIPBASE - ZIPFILE=$ZIPFILE
       fi

       if [ ! -d "./${ZIPBASE}" ] ; then  
          mkdir "${ZIPBASE}"	
       fi

       unzip -o "${ZIPFILE}" -d "${ZIPBASE}" 

       if [ $? -eq 0 ] ; then
          if [ ! -d tobedeleted ] ; then 
             mkdir tobedeleted
          fi
          mv "${ZIPFILE}" tobedeleted 
       else
          rm -rf "${ZIPBASE}"
       fi
    done




    for each in `find . -type f -name \*.[EeRr][XxAa][EeRr] -maxdepth 1 -printf "%p\n"|tr " " "?"`  `find . -name \*.001 -maxdepth 1 -printf "%p\n"|tr " " "?"`
    do
       echo "Found: ${each}"
       RARFILE=""
       RARFILE="`echo ${each} | grep -v -i part`"

       #
       # Various checks to see if the currently selected file
       # is a candidate to have rar run against it to expand it.
       # Currently supported are: .part001.rar, .exe, .001
       #


       if [ "${RARFILE}" == '*.[0EeRr][0XxAa][1EeRr]' ] ; then
          RARFILE=""
       fi

       if [ ! -n "${RARFILE}" ] ; then 
          RARFILE=`echo ${each} | egrep -i [p][a][r][t]0*0*1\.rar$`
       fi

       if [ ! -n "${RARFILE}" ] ; then
          RARFILE=`echo ${each} | egrep -i .exe$`
       fi

       if [ ! -n "${RARFILE}" ] ; then
          RARFILE=`echo ${each} | egrep -i .001$`
       fi

       #
       # The big rar unarchiving loop - Where the real work gets done
       #
       if [ -n "${RARFILE}" ] ; then
          echo "Processing ${RARFILE}"
          RARBASE="`echo "${RARFILE}" |sed s/.[0Rr][0Aa][1Rr]$//|sed s/.[Pp][Aa][Rr][Tt][0-9]*//| cut -f2 -d/`"


          # If there is a "missing" entry for the rarbase name in the par-report
          # then just go on and test the archive anyways. If a part is
	  # missing, then we know not to waste the CPU time testing it. 
          COMPLETED="`grep "${RARBASE}" par-report.txt | grep missing`"
          #
	  # But this is only true the 2nd time par2cmdline is ran, or if
	  # using the original parchive utility. Otherwise, we need to 
          # search for the string 'Repair is possible'
          # 
          if [ -n "`grep 'Repair is possible' par-report.txt`" ] ; then
             COMPLETED=""
          fi

          if [ ! -n "${COMPLETED}" ] ; then
             if [ ! -n "${NOTEST}" ] ; then 
                echo "testing ${RARFILE}"
                rar t -av- -y -- "${RARFILE}"
             else
                echo "Skipping Archive Test"
             fi

 	     if [ $? -eq 0 ] ; then
                echo "Archive is complete - unarchiving..."
	        if [ -n "$NOUNRAR" ] ;  then
                   echo would try to unrar ${RARFILE} now if not in NOUNRAR mode
                 else
		   FIXEDBASE=`echo ${RARBASE}|tr " " .`
	           mkdir "${FIXEDBASE}"
             
                   rar x -av- -p- -o- -y -- "${RARFILE}" "${FIXEDBASE}"
                   if [ $? -eq 0 ] ; then 
                      echo ${RARFILE} successfully unarchived.
		      if [ ! -d ./tobedeleted ] ; then
                         mkdir tobedeleted 
                      fi
                      mv "${FIXEDBASE}"*[PpRr][Aa0-9][Rr0-9] tobedeleted
                      mv "${RARBASE}"* "${FIXEDBASE}" 2>/dev/null
                      cp -u *.[Nn][Ff][Oo] "${FIXEDBASE}" 2>/dev/null
		      if [ ! -n "${DO_NOT_DELETE}" ] ; then
                      	rm -rf tobedeleted
 		      fi
                   else
                       echo unarchiving of ${RARFILE} failed
			# Clean up after ourselves
                       rm -rf "${FIXEDBASE}"
		       rm nohup.out
                   fi
                fi
            fi
          fi
       fi
    done


#
# fi
# End NOUNRAR Section


    for eachmpg in *.[Mm][Pp][Gg].001
    do
       if [ ! -f "${eachmpg}" ] ; then
          break
       fi
       # Break out in case we try to processes a non-existing file. 

       MPGBASE=`echo "${eachmpg}" |sed s/.001$//`
       if [ -f "./${MPGBASE}" ] ; then
          if [ ! -n "${QUIET}" ] ; then
             echo ${MPGBASE} already exists - moving to ${MPGBASE}.old
	  fi
          mv "${MPGBASE}" "${MPGBASE}.old"
       fi
       if [ ! -n "${QUIET}" ] ; then
          echo "attempting to create ${MPGBASE} - from base parts starting with ${eachmpg}"
       fi
       for each in ${MPGBASE}.[0-9][0-9][0-9]
        do 
          if [ -n "${VERBOSE}" ] ; then
             echo "Joining ${each} to ${MPGBASE}"
          fi
          cat ${each} >> ${MPGBASE}
        done
    done





#    if [ -n "${DEBUG}" ] ; then
#       echo starting search for mpeg VCD or SVCD files. 
#    fi

# 
#The mpeg stuff is broke
#
#    MPEGFILES=""
#    MPEGFILES=`find . -iregex .*\.mpe*g -mindepth 2 -maxdepth 2`
#
#    if [ -n "${DEBUG}" ] ; then
#       echo MPEGFILES=${MPEGFILES}
#    fi   
#


#    if [ -n "${MPEGFILES}" ] ; then
#        
#    for each in `echo "${MPEGFILES} " | cut -f2 -d/`
#        do
#          BASEDIR=`echo "${BASEDIR} ${each} "`
#        done

#    for each in ${BASEDIR}
#        do
#          echo EACH=${each}
#          cd ${each}
#          echo PWD=`pwd`
#          MPEGS=`find . -iregex .*\.mpe*g -mindepth 1 -maxdepth 1`
#           vcdimager --iso-volume-label="`echo ${each}|tr . _`" --bin-file="./${each}.bin" --cue-file="./${each}.cue" ${MPEGS}  
#          vcdimager -v --iso-volume-label=${each} --bin-file=./${each}.bin --cue-file=./${each}.cue *.[Mm][Pp][EeGg]*
# Commented out the VCDIMAGER
# stuff 'cuz ckdls is crashing right around here.

#        done
#    fi 


    # Added support for moving finished unrared directories to the "done"
    # area.
#     find . -type d -exec mv {} ${FINISHED_DIR} \;

    cd "${STARTDIR}"


done


# Remove empty directories.


for each in `find ${DIR_PARAM} -type d -printf \"%p\"\n`
do
    rmdir "${each}"  2>/dev/null
done





#
# To Do:

#
# Make program names, command line parameters, and directory paths
# variables in the header. 
#

#
# Get all the command line parameters working.
#
# Make VCD and SVCD images
#
# Autoburn files
#
# LCD display support


