LinuxQuestions.org
Support LQ: Use code LQ3 and save $3 on Domain Registration
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices

Reply
 
Search this Thread
Old 12-18-2012, 10:19 PM   #1
jmxp69
LQ Newbie
 
Registered: Dec 2012
Posts: 1

Rep: Reputation: Disabled
HandbrakeCLI Script Review/Comments


Hello forum,

In my efforts to simplify the process of ripping dvd's for use on Plex, I've written the following script and I'm interested in feedback on how I can improve it.

I'm not a professional programmer by any stretch, so please forgive my inability to adhere to strict standards.

I'd like to avoid debate on Handbrake options on the command line. If you use this script, feel free to use what makes you happy. The options I used work well for me. I get reasonable video quality and DD 5.1/DTS to my receiver via Plex.

What I'm more interested in learning about is if there are better/more error handling options, or coding standards that will improve the accuracy and success rate of this script.

So far I've tested it with a half dozen DVDs and it seems to work pretty well. I'd like to add some commandline options and commandline help with -h but I don't need help there (just yet). I simply haven't gotten to it. Open to suggestions and feedback on this topic.

Appreciate any guidance in advance,

J

Code:
#!/bin/sh

#################################################################################
# Copywright (c) 2012 John Hopke 	                                 	#
# Script: autorip.sh								#
# Revision: 1.0									#
# 										#
# This script is intended to automate ripping DVD's using HandBrakeCLI.		#
# Logging to syslog and e-mail notifications of the result is provided.		#
# The auto-rip.runfile is created in the output directory so you can follow 	#
# the script's progress (useful for testing/debugging). 			#
# Syslog entries are for adminstrators to monitor use.				#
# 										#
# Initially I wanted udev to invoke the script, but that didn't work well.	#
# Another option is to invoke via crontab. It's safe to run every x minutes	#
# because the script exits if it finds another instance running. It also will	#
# avoid re-ripping movies if you don't eject the media after ripping		#
# 										#
# There are no commandline paramters. I'll add those in an upcoming release.	#
# 										#
# The ideal outcome is an .mkv rip with dolby digital (DD/AC3) and DTS passthru	#
# to be placed in a folder monitored by Plex or other media server		#
#										#
# Additional Tools Required:							#
# - Working HandBrakeCLI install and requisite dvd tools (libdvdread4)		#
# - heirloom-mailx								#
# - lsdvd									#
#										#
#    This program is free software: you can redistribute it and/or modify	#
#    it under the terms of the GNU General Public License as published by	#
#    the Free Software Foundation, either version 3 of the License, or		#
#    (at your option) any later version.					#
#										#
#    This program is distributed in the hope that it will be useful,		#
#    but WITHOUT ANY WARRANTY; without even the implied warranty of		#
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the		#
#    GNU General Public License for more details.				#
#										#
#    You should have received a copy of the GNU General Public License		#
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.	#
#										#
#################################################################################


# Use lowercase y or n for yes/no options

DRYRUN=n			# If set to yes the entire script runs, but the HandBrake command isn't processed
EJECT=n				# If set to yes, the disc will be ejected at successful termination
EMAILYN=y			# If set to yes, Email will be sent at successful termination
THRESHOLD=600			# Set minimum filesize for rips in MB. i.e. Rips smaller than 200MB will trigger alert/notification in email
EMAIL=to@you.com		# Set to the user who should recieve email notification
FROM=from@you.com	# Set from address for email notification
MAILER=/usr/bin/mail		# Location of your mail program
MESSAGE=/tmp/autorip.msg	# Temporary storeage for email message
LOGFILE=/var/log/syslog		# Location of the logfile auto-rip should use
OUTDIR=/mnt/RaidVol/movies-in	# Location where you want the rips to be stored
TMP=/tmp
LOGDIR=$OUTDIR/riplogs
TEMPSTAT=auto-rip.runfile
STATFILE=$OUTDIR/$TEMPSTAT	# Status file (useful to see what happened per rip
PIDFILE=/tmp/auto-rip.pid	# PID to ensure we don't run more than one script at a time
DEVICE=/dev/sr0			# Your DVD drive

### No other variables need to be set below this line. ###

# Setup various timestamps used for logging and notifications
NOW="$(date +%b) $(date +%d) $(date +%T) $(hostname -s) DVDRIP [$$]:"
TS="$(date +%m-%d-%y-%T)_DVDRIP"
TIME="$(date +%T)"


# If running, die.
# This really needs to be the first thing to do. Things get messy if fiddled.
if [ -f "$PIDFILE" ];
then
	echo $NOW "PIDFILE exists, script already appears to be running. Exiting!" >> $LOGFILE
	echo $NOW "Remove $PIDFILE to force run." >> $LOGFILE
	exit
fi

# First few lines of e-mail notification with timestamp
echo "Notice: The DVD Autorip service on $(hostname) found a DVD and attempted to rip it. Details of this action follow:\n" > $MESSAGE
echo "Process start	: $TIME" >> $MESSAGE

# Send process ID to pidfile (Can be used by other scripts)
echo $$ > $PIDFILE
cat /dev/null > $STATFILE 
sleep 1
echo "==> Process Start: $TIME" > $STATFILE
echo $NOW "DVD Auto-Rip Started." >> $LOGFILE


# Does the disc have media? Doesn't make sense to go any further if not.
HASMEDIA=`udisks --show-info $DEVICE |grep "has media"|awk '{print $3}'`
if [ $HASMEDIA -eq 0 ]; then 
	echo $NOW "No media detected in the DVD drive. Exiting!" >> $LOGFILE
	echo "==> No media detected in the DVD drive. Exiting!" >> $STATFILE
	rm $PIDFILE
	exit
else
	echo $NOW "Drive contains media--continue." >> $LOGFILE
	echo "==> Drive has media" >> $STATFILE
fi

# Read the title and set output filename.
INTITLE=`lsdvd $DEVICE 2>&1| grep "Disc Title:" | sed -e 's/\..*$//' | cut -b 13-`
TITLE=$( echo "$INTITLE" | tr -s '[:upper:]'  '[:lower:]')
echo "==> Disc title: $TITLE" >> $STATFILE
echo $NOW "DVD RIP Started for Disc: $TITLE" >> $LOGFILE
echo "Title found	: $TITLE" >> $MESSAGE #prep email


OUTFILE=$TITLE.mkv
echo "==> Output filename: $OUTFILE" >> $STATFILE
echo "==> Output directory: $OUTDIR" >> $STATFILE

# This is mostly an error trap. Some discs fail to return a reasonable title.
if [ $OUTFILE = ".mkv" ]; then
	echo "==> [ERROR] Unable to determine title of movie. Terminating!" >> $STATFILE
	echo $NOW "[ERROR] Unable to determine title of movie. Terminating!" >> $LOGFILE
	rm $PIDFILE
	exit
fi

# Setup <filepath/filename>
TMPOUT=$TMP/$OUTFILE
OUTPUT=$OUTDIR/$OUTFILE
echo "==> Full Path of rip: $OUTPUT" >> $STATFILE
echo $NOW "Planned output file $OUTPUT" >> $LOGFILE


# If the proposed output file exists, this disc may have already been ripped, so let's not do it again.
echo "==> Checking to ensure this title hasn't already been ripped" >> $STATFILE
if [ -f $OUTPUT ];
	then
	   echo "==> [ERROR] Movie already ripped" >> $STATFILE
	   echo $NOW "[ERROR] $OUTFILE exists in $OUTDIR/ Terminating!" >> $LOGFILE
	   echo "==> [ERROR] $OUTPUT already exists. Terminating!!" >> $STATFILE
	   rm $PIDFILE
	   exit
	else
	   echo $NOW "No $OUTFILE in $OUTDIR, continuing" >> $LOGFILE
fi

# Time for the heavy lifting.
commandline="HandBrakeCLI -i $DEVICE -c 1 -o $TMPOUT -m -E copy --audio-copy-mask ac3,dts --audio-fallback ffac3 -e x264 -q 20 -B 160"
if [ "$DRYRUN" = "y"  ];
	then
	 echo "==> Dryrun indicated. Handbrake will not execute" >> $STATFILE
	 echo "==> Commandline would have been: $commandline" >> $STATFILE
	 echo "==> Dryrun set. No $OUTPUT expected" >> $STATFILE
        echo $NOW "Dryrun indicated. Command would have been: $commandline" >> $LOGFILE
	else #Perform the RIP
	 echo "==> Dryrun NOT Indicated. Time to make the doughnuts" >> $STATFILE
	 echo "==> Launching Handbrake" >> $STATFILE
	 echo "==> Commandline is: $commandline" >> $STATFILE
	 echo $NOW "Processing $commandline" >> $LOGFILE
	 $commandline
	 mv $TMPOUT $OUTDIR
	 echo "==> Ripped movie is $OUTPUT" >> $STATFILE
fi


# Transcode is done. Housekeeping and notification time: 
# - send email notification.
# - eject disc if set to Y above.
# - move auto-rip.runfile to ripname.runfile (to preserve outcome of previous sessions)
# - clean up temp

echo $NOW "DVD Auto-Rip completed. Post-rip analysis and clean-up" >> $LOGFILE
echo "==> Analyze output, and clean-up" >> $STATFILE

FILESIZE=`echo "$(stat -c%s "$OUTPUT") / 1048578"|bc`
if [ "$EMAILYN" = "y" ];
	then
	  echo "==> Email flag set to yes, result sent to $EMAIL" >> $STATFILE
	  echo $NOW "Email flag set to yes, sending notification to $EMAIL" >> $LOGFILE
	  SUBJECT="DVD RIP Completed! $TIME"
	  echo "Output File	: $OUTFILE" >> $MESSAGE
	  echo "Location 	: $OUTDIR" >> $MESSAGE
	  echo "Filesize		: $FILESIZE MB" >> $MESSAGE
	  # WARN if the output filesize is lower than user set threshold
	  if [ $FILESIZE -lt $THRESHOLD ]; then
		echo "==> [ALERT] $OUTFILE is $FILESIZE MB (Less than $THRESHOLD MB) Not a good sign." >> $STATFILE
		echo $NOW "[ALERT] $OUTPUT is $FILESIZE MB (less than $THRESHOLD MB). Adding warning message to email notification" >> $LOGFILE
		echo "[ALERT]		$OUTFILE is $FILESIZE MB. User threshold is $THRESHOLD MB. $OUTFILE appears too small.\n" >> $MESSAGE
	  else
	 	echo "==> Filesize is $FILESIZE MB which is greater than threshold of $THRESHOLD MB. Looking good!" >> $STATFILE
	  fi

	  echo "Logfile		: $LOGDIR/$TITLE.$TS.log" >> $MESSAGE
	  echo "Process End	: $TIME" >> $MESSAGE
	  $MAILER -r "$FROM" -s "$SUBJECT" "$EMAIL" < $MESSAGE
	else
	  echo "==> Email flag off, no notifications sent" >> $STATFILE
	  echo $NOW "Email flag off, no notifications will be sent" >> $LOGFILE
fi

if [ "$EJECT" = "y" ];
	then
	  echo "==> Ejecting  DVD" >> $STATFILE
	  echo $NOW "Rip complete, eject Disc" >> $LOGFILE
	  eject $DEVICE
	else
	  echo "==> DVD Eject disabled" >> $STATFILE
	  echo $NOW "DVD Eject set to no, eject manually" >> $LOGFILE
fi

# Clean up files
if [ -f $PIDFILE ]; then rm $PIDFILE
fi

if [ -f $MESSAGE ]; then rm $MESSAGE 
fi

echo "==> Auto-rip exited cleanly" >> $STATFILE
echo "==> Process End: $TIME" >> $STATFILE
if [ ! -d "$LOGDIR" ]; then mkdir $LOGDIR
fi
cat $STATFILE > $LOGDIR/$TITLE.$TS.log
echo $NOW "Storing results in $LOGDIR/$TITLE.$TS.log" >> $LOGFILE
echo $NOW "DVD Rip can be found in $OUTPUT" >> $LOGFILE
echo $NOW "DVD Rip complete. Exiting!" >> $LOGFILE

Last edited by jmxp69; 12-19-2012 at 12:52 AM.
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
[SOLVED] How to use HandBrakeCli to encode video in a certain time duration? Hak5fan Linux - General 1 01-28-2012 04:13 PM
Request For Comments on Firewall script niels.horn Linux - Security 7 04-04-2009 02:32 PM
bash script to delete all comments after '#'?? dr44mon Linux - Newbie 4 01-30-2009 03:12 PM
looking for script - strip out all # comments itsjustme Programming 3 03-11-2004 10:57 AM
Program (or Script) to download Slashdot Article with Comments LinuxGeek Linux - General 1 08-24-2002 03:29 AM


All times are GMT -5. The time now is 04:21 AM.

Main Menu
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
identi.ca: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration