#!/bin/sh
#Set these here otherwise path problems break the script when run from cron
FIND=/mod/bin/busybox/find
GREP=/mod/bin/busybox/grep
SED=/mod/bin/busybox/sed
LSOF=/mod/bin/lsof
BASENAME=/mod/bin/busybox/basename
RMDIR=/mod/bin/busybox/rmdir
MV=/mod/bin/busybox/mv
TR=/mod/bin/busybox/tr
CUT=/mod/bin/busybox/cut
HMT=/mod/bin/hmt
RENAME=1 #Enable or disable file renaming based on EPG data
#Needed to stop the list using spaces as delimiters
IFS=$'\n'
#Despite the pipe following the next find, the IFS still needs to be set
#Find all the top level directories in "My Video" that contain
#a .series file and iterate through them
$FIND /media/My\ Video/ -maxdepth 2 -mindepth 2 -name '.series' | $SED 's/\/.series$//g' | while read dir; do
#Strip out the series name from the directory name and look for
#other directories with the same name
series=`$BASENAME "$dir"`
echo "Checking $dir"
location=`$FIND /media/My\ Video/ -mindepth 2 -type d -name "$series"`
#$location is only set if another directory has been found with the same name
if [ -n "$location" ]; then
echo "Filing for $location"
#Use the hmt files to identify the episode base filename and strip off the suffix using sed
for episodefile in `$FIND "$dir/" -name '*.hmt' | $SED 's/.hmt$//'`
do
#Find and move all the files for this episode, if they are not in use
episode=`$BASENAME "$episodefile"`
inuse=`$LSOF | $GREP "$episode".ts`
if [ -n "$inuse" ]; then
echo "$episodefile is in use - skipping"
else
#Rename the episodes so that we have a name from the first X characters of the EPG
if [ "$RENAME" -eq 1 ]; then
echo "Renaming the episode to give it a nice name"
epg=`$HMT "$dir/$episode" | $GREP '^EPG:' | $CUT -d: -f2`
epg="`echo ${epg:0:40}`" # TRIM THE FILENAME DOWN TO 40 CHARACTERS
$HMT +settitle="$epg" "$dir/$episode.hmt"
echo " HMT for $episode.hmt renamed title to $epg"
fi
#Now go and move the file to the new location
echo "Moving $episode to $location"
$MV "$dir/$episode".* "$location"
fi
done
if [ "$(ls $dir)" ]; then
#There is probably another episode being recorded
#we don't want to interfere, so do nothing
echo "Series directory not empty"
else
#.series is a hidden file, and the only hidden file that should exist
#if there are no other files in the directory, move .series as well
#and then remove the series directory at the top level - the filing is now done
#.series has to be moved last, in case the box powers down mid script
#in which case, re-running it should still cleanly finish the process
$MV $dir/.series $location
echo "Removing empty series directory"
$RMDIR "$dir"
fi
fi
done
#And show all the series that have been processed in the last day
echo "Recently filed:"
$FIND /media/My\ Video/ -mindepth 3 -mtime -1 -name '.series' | $SED 's/\/.series$//g'