Archive:MythicalLibrarian: Difference between revisions

From Official Kodi Wiki
Jump to navigation Jump to search
>Outleradam
No edit summary
>Outleradam
No edit summary
Line 1: Line 1:
#!/bin/bash
#!/bin/bash
   
   
  #mythicalLibrarian by Adam Outler
  #mythicalLibrarian by Adam Outler
Line 69: Line 69:
  # optional: install libnotify-bin with "apt-get install libnotify-bin"  
  # optional: install libnotify-bin with "apt-get install libnotify-bin"  
  #
  #
  #Notifications:
  #Ubuntu Notifications:
  # In order for mythicalLibrarian to send notifications to the GNOME desktop, it must have no-password sudo access.  It uses
  # In order for mythicalLibrarian to send notifications to the GNOME desktop, it must have no-password sudo access.  It uses
  # this access strictly to send complete, moving and failure status notifications.  Because this program is launched by the
  # this access strictly to send complete, moving and failure status notifications.  Because this program is launched by the
Line 76: Line 76:
  # Notifications are an optional feature
  # Notifications are an optional feature
  #
  #
#XBMC Notifications:
# If options are enabled, mythicalLibrarian will send a http request to a XBMC Server.  In order for this to work XBMC you
# must ensure that System-service-allow programs on other..
  #Show Name Translation
  #Show Name Translation
  # The user may elect to create a file in the mythicalLibrarian/ working folder which will then translate any recorded
  # The user may elect to create a file in the mythicalLibrarian/ working folder which will then translate any recorded
Line 94: Line 99:
   
   
  #######################USER SETTINGS##########################
  #######################USER SETTINGS##########################
  ###Stand-alone functions###
  ###Stand-alone mode values###
  #MoveDir is the folder which mythicalLibrarian will move the file.  No trailing / is accepted eg. "~/videos"
  #MoveDir is the folder which mythicalLibrarian will move the file.  No trailing / is accepted eg. "~/videos"
  MoveDir=/home/mythtv/NAS/Video/shows
  MoveDir=/home/mythtv/NAS/Video/shows
Line 106: Line 111:
  #Create symlink in original dir from file after MOVE. Do not move just LINK original in MoveDir(overrides moving), Simlinking Disabled  
  #Create symlink in original dir from file after MOVE. Do not move just LINK original in MoveDir(overrides moving), Simlinking Disabled  
  SYMLINK=MOVE
  SYMLINK=MOVE
  #DailyReport provides a log of shows added to your library per day.
  #DailyReport provides a log of shows added to your library per day. Enabled|Disabled
  DailyReport=Enabled
  DailyReport=Enabled
  #Internet access Timeout in seconds: Default Timeout=50 (seconds)
  #Internet access Timeout in seconds: Default Timeout=50 (seconds)
Line 112: Line 117:
  #Update database time in secconds, Longer duration means faster processing time and less strain on TheTvDb. Default='84000' (1 day)
  #Update database time in secconds, Longer duration means faster processing time and less strain on TheTvDb. Default='84000' (1 day)
  UpdateDatabase=84000
  UpdateDatabase=84000
  #mythicalLibrarian working file dir: Default is "~/mythicalLibrarian"
  #mythicalLibrarian working file dir: Default is mythicalLibrarian=~/mythicalLibrarian
  mythicalLibrarian=~/mythicalLibrarian
  mythicalLibrarian=~/mythicalLibrarian
  #FailSafe mode will enable symlinks to be formed in FailSafeDir if the move or symlink operation fails.
  #FailSafe mode will enable symlinks to be formed in FailSafeDir if the move or symlink operation fails.
Line 125: Line 130:
  DEBUGMODE=Enabled
  DEBUGMODE=Enabled
   
   
  ###Notifications###
  ###Reporting/Communications###
  #The following line tells mythicalLibrarian to send a notification to GNOME Desktop upon completion. Enabled|Disabled
  #The following line tells mythicalLibrarian to send a notification to GNOME Desktop upon completion. Enabled|Disabled
  Notify=Enabled
  Notify=Enabled
  #Send a notification to XBMC to update and cleanup library upon sucessful move job Enabled|Disabled
  #Send a notification to XBMC to Update library upon sucessful move job Enabled|Disabled
  XBMCAutomate=Enabled
XBMCUpdate=Enabled
#Send a notification to XBMC to cleanup the library upon sucessful move job Enabled|Disabled
  XBMCClean=Enabled
  #Send Notifications to XBMC UI when library is updated Enabled|Disabled
  #Send Notifications to XBMC UI when library is updated Enabled|Disabled
  XBMCNotify=Enabled
  XBMCNotify=Enabled
  #Ip Address and port for XBMC Notifications
  #Ip Address and port for XBMC Notifications Eg.XBMCIP=192.168.1.110:8080
  XBMCIP=192.168.1.110:8080
  XBMCIP=192.168.1.110:8080
    
    
  ###Database settings###  
  ###MythTV Database settings###  
  #Database access Enabled|Disabled
  #Database access Enabled|Disabled
  Database=Enabled
  Database=Enabled
Line 189: Line 196:
   
   
  #Check and make doover.sh if it does not exist
  #Check and make doover.sh if it does not exist
  if [ ! -f "$mythicalLibrarian/doover.sh" ]; then
  test ! -f "$mythicalLibrarian/doover.sh" && echo 'rm "'$mythicalLibrarian'"/doover.sh'>$mythicalLibrarian/doover.sh
echo 'rm "'$mythicalLibrarian'"/doover.sh'>$mythicalLibrarian/doover.sh
 
fi
  #Function daily report data
  #Function daily report data
  dailyreport() {
  dailyreport() {
  if [ $DailyReport = Enabled ]; then
  if [ $DailyReport = Enabled ]; then
  if [ ! -d "$mythicalLibrarian/DailyReport" ]; then
  test ! -d "$mythicalLibrarian/DailyReport" && mkdir "$mythicalLibrarian/DailyReport"  
mkdir "$mythicalLibrarian/DailyReport"  
fi
  reportfilename=`date +%Y-%m-%d`
  reportfilename=`date +%Y-%m-%d`
  reporttime=`date +%T`
  reporttime=`date +%T`
Line 215: Line 217:
  if [ -f "$3/arbitraryfile.ext" -a -s "$3/arbitraryfile.ext" ]; then
  if [ -f "$3/arbitraryfile.ext" -a -s "$3/arbitraryfile.ext" ]; then
  rm "$3/arbitraryfile.ext"
  rm "$3/arbitraryfile.ext"
  if [ ! -f "$3/arbitraryfile.ext" ]; then
  test ! -f "$3/arbitraryfile.ext" && TMoveDirWritable=1 || TMoveDirWritable=0
TMoveDirWritable=1
elif [ -f "$3/arbitraryfile.ext" ]; then
TMoveDirWritable=0
fi
  else
  else
  TMoveDirWritable=0
  TMoveDirWritable=0
Line 229: Line 227:
  fi
  fi
  }
  }
 
#Function XBMC Automate handles all communication with XBMC 
XBMCAutomate () {
#Send notification to XBMC, Update Library, Clean Library
test "$XBMCNotification" = "Enabled" && curl "http://$XBMCIP/xbmcCmds/xbmcHttp?command=ExecBuiltIn(Notification(mythical%20Librarian%2Cadding%20program%20$tvdbshowname%20to%20library!))"
test "$XBMCUpdate" = "Enabled" && curl "http://$XBMCIP/xbmcCmds/xbmcHttp?command=ExecBuiltIn(UpdateLibrary(video))"
test "$XBMCClean" = "Enabled" && curl "http://$XBMCIP/xbmcCmds/xbmcHttp?command=ExecBuiltIn(CleanLibrary)"
}
  #####MAINTENANCE#####
  #####MAINTENANCE#####
   
   
  #Loop through the list of created comskip files and remove orphans.
  #Loop through the list of created comskip files and remove orphans.
  if [ -f "$mythicalLibrarian/comskiplog.tracking" ]; then
  if [ -f "$mythicalLibrarian/comskiplog.tracking" ]; then
mythicalLibrarianCounter=0
  while read line
  while read line
  do
  do
  mythicalLibrarianCounter=`expr $mythicalLibrarianCounter + 1`
  let mythicalLibrarianCounter=$mythicalLibrarianCounter+1
  FileToCheck=`sed -n "$mythicalLibrarianCounter"p "$mythicalLibrarian/comskiplog.tracking"`
  FileToCheck=$line
  FileToCheckOriginalDirName=`dirname "$FileToCheck"`
  FileToCheckOriginalDirName=`dirname "$FileToCheck"`
  FileToCheckBaseName=`basename $FileToCheck`
  FileToCheckBaseName="${FileToCheck##*/}"
  FileToCheckBaseName=${FileToCheckBaseName%.*}
  FileToCheckBaseName="${FileToCheckBaseName%.*}"
  if [ "$FileToCheck" != "" ]; then
  if [ ! -z "$FileToCheck" ]; then
echo "f2cbn$FileToCheckBaseName dirname$FileToCheckOriginalDirName ftc$FileToCheck cnt$mythicalLibrarianCounter" >>"$mythicalLibrarian"/output.log
  FileToCheckLS=`ls "$FileToCheckOriginalDirName"|grep "$FileToCheckBaseName."|sed -n 2p`
  FileToCheckLS=`ls "$FileToCheckOriginalDirName"|grep "$FileToCheckFileBaseName\."|sed -n 2p`
  if [ -z "$FileToCheckLS" ]; then
  if [ "$FileToCheckLS" = "" ]; then
rm $FileToCheck
  echo "MAINTENANCE FOUND NO MOVIE: REMOVING COMSKIP $FileToCheck">>"$mythicalLibrarian"/output.log
  echo "ORPHAN FOUND $FileToCheck">>"$mythicalLibrarian"/output.log
#rm $FileToCheck
  elif [ ! -z "$FileToCheckLS" ]; then
  elif [ "$FileToCheckLS" != ""]; then
  echo "$FileToCheck">>"$mythicalLibrarian/comskiplog.tracking2"
  echo ORPHAN FOUND: $FileToCheck>>"$mythicalLibrarian/comskiplog.tracking2"
  fi
  fi
  fi
  fi
Line 261: Line 270:
   
   
  #Get information if database is enabled
  #Get information if database is enabled
  if [ "$Database" = Enabled ]; then  
  if [ "$Database" = "Enabled" ]; then  
   
   
  #get chanid for recordings to identify program table
  #get chanid for recordings to identify program table
Line 278: Line 287:
  #if the ProgramID does not meet criteria, then end the program
  #if the ProgramID does not meet criteria, then end the program
  if [ "$ProgramIDType" = "Generic Episode With No Data" ]; then
  if [ "$ProgramIDType" = "Generic Episode With No Data" ]; then
  echo "PROGRAM GUIDE DATA IS NOT COMPLETE.  TYPE: $ProgramIDType">>"$mythicalLibrarian"/output.log
  echo "GENERIC GUIDE DATA WAS SUPPLIED TYPE: $ProgramIDType $1, $2">>"$mythicalLibrarian"/output.log
  echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%">>"$mythicalLibrarian"/output.log
  echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%">>"$mythicalLibrarian"/output.log
  echo "%%%%%%%%%%GENERIC GUIDE DATA WAS SUPPLIED $1, $2">>"$mythicalLibrarian"/output.log
  echo "%%%%%%%%%%%%%%%%%%%PROGRAM GUIDE DATA IS NOT COMPLETE%%%%%%%%%%%%%%%%%%%%">>"$mythicalLibrarian"/output.log
  echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%">>"$mythicalLibrarian"/output.log
  echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%">>"$mythicalLibrarian"/output.log
   if [ $Notify = "Enabled" ]; then
   test $Notify = "Enabled" && sudo -u "$NotifyUserName" /usr/local/bin/librarian-notify-send "mythicalLibrarian Guide error" "Could not obtain enough information for library: $ProgramIDType" error
sudo -u "$NotifyUserName" /usr/local/bin/librarian-notify-send "mythicalLibrarian Guide error" "Could not obtain enough information for library: $ProgramIDType" error
fi
   echo $mythicalLibrarian'/mythicalLibrarian.sh "'$1'" "'$2'" "'$3'"'>>$mythicalLibrarian/doover.sh
   echo $mythicalLibrarian'/mythicalLibrarian.sh "'$1'" "'$2'" "'$3'"'>>$mythicalLibrarian/doover.sh
  exit 1
  exit 1
Line 305: Line 312:
   
   
  #Blank year if it is invalid
  #Blank year if it is invalid
  if [ "$MovieAirDate" != "" ]; then
  test ! -z "$MovieAirDate" -a "$MovieAirDate" -lt "1900" && MovieAirDate=$null
if [ "$MovieAirDate" -lt "1900" ]; then
MovieAirDate=""
fi
fi
   
   
  #Report found data
  #Report found data
  echo RECSTART:$ShowStartTime MOVIEYEAR:$MovieAirDate SERIESDATE:$OriginalAirDate  
  echo RECSTART:$ShowStartTime MOVIEYEAR:$MovieAirDate SERIESDATE:$OriginalAirDate  
  echo PROGRAMID:$ProgramID ShowCategory:$ShowCategory
  echo PROGRAMID:$ProgramID ShowCategory:$ShowCategory  
   
   
  #####COMSKIP DATA#####
  #####COMSKIP DATA#####
  #Remove old and generate a comskip Start list
  #Remove old and generate a comskip Start list
  echo "" >$mythicalLibrarian/markupstart.txt
  echo $null >$mythicalLibrarian/markupstart.txt
  mysql -u$MySQLuser -p$MySQLpass -e "use '$MySQLMythDb' ; select mark from recordedmarkup where starttime like '$ShowStartTime' and chanid like '$ChanID' and type like "4" ; " |replace "mark" ""|replace " " "">>$mythicalLibrarian/markupstart.txt
  mysql -u$MySQLuser -p$MySQLpass -e "use '$MySQLMythDb' ; select mark from recordedmarkup where starttime like '$ShowStartTime' and chanid like '$ChanID' and type like "4" ; " |replace "mark" ""|replace " " "">>$mythicalLibrarian/markupstart.txt
   
   
  #Remove old and generate comskip Stop list
  #Remove old and generate comskip Stop list
  echo "" >$mythicalLibrarian/markupstop.txt
  echo $null >$mythicalLibrarian/markupstop.txt
  mysql -u$MySQLuser -p$MySQLpass -e "use '$MySQLMythDb' ; select mark from recordedmarkup where starttime like '$ShowStartTime' and chanid like '$ChanID' and type like "5" ; " |replace "mark" ""|replace " " "">>$mythicalLibrarian/markupstop.txt
  mysql -u$MySQLuser -p$MySQLpass -e "use '$MySQLMythDb' ; select mark from recordedmarkup where starttime like '$ShowStartTime' and chanid like '$ChanID' and type like "5" ; " |replace "mark" ""|replace " " "">>$mythicalLibrarian/markupstop.txt
   
   
Line 336: Line 337:
  StartData=`sed -n "$mythicalLibrarianCounter"p "$mythicalLibrarian/markupstart.txt"`
  StartData=`sed -n "$mythicalLibrarianCounter"p "$mythicalLibrarian/markupstart.txt"`
  StopData=`sed -n "$mythicalLibrarianCounter"p "$mythicalLibrarian/markupstop.txt"`
  StopData=`sed -n "$mythicalLibrarianCounter"p "$mythicalLibrarian/markupstop.txt"`
  if [ "$StopData" != "" ]; then
  if [ ! -z "$StopData" ]; then
  echo "$StartData $StopData">>"$mythicalLibrarian"/markupframes.txt
  echo "$StartData $StopData">>"$mythicalLibrarian"/markupframes.txt
  CommercialMarkup="Created"
  CommercialMarkup="Created"
Line 343: Line 344:
  done <"$mythicalLibrarian/markupstop.txt"
  done <"$mythicalLibrarian/markupstop.txt"
  fi
  fi
  fi  
  fi  
   
   
Line 350: Line 349:
   
   
  #####SEARCH FOR SHOW NAME#####
  #####SEARCH FOR SHOW NAME#####
  if [ "$MovieAirDate" = "$null" ]; then
  if [ ! -z "$2" -o "$mythicalLibrarianProgramIDCheck" = "EP" ]; then
  echo "SEARCHING: www.TheTvDb.com SHOW NAME: $ShowName EPISODE: $epn">>"$mythicalLibrarian"/output.log
  echo "SEARCHING: www.TheTvDb.com SHOW NAME: $ShowName EPISODE: $epn">>"$mythicalLibrarian"/output.log
  echo "FILE NAME: $3">>"$mythicalLibrarian"/output.log
  echo "FILE NAME: $3">>"$mythicalLibrarian"/output.log
Line 368: Line 367:
  seriesid=`sed -n $serieslinenumber'p' $mythicalLibrarian/sid.txt|grep -m1 ^`
  seriesid=`sed -n $serieslinenumber'p' $mythicalLibrarian/sid.txt|grep -m1 ^`
  NewShowName=`sed -n $serieslinenumber'p' $mythicalLibrarian/shn.txt|grep -m1 ^`
  NewShowName=`sed -n $serieslinenumber'p' $mythicalLibrarian/shn.txt|grep -m1 ^`
  elif [ "$MovieAirDate" != "$null" ]; then
  elif [ -z "$MovieAirDate" ]; then
  NewShowName=$1
  NewShowName=$1
  fi
  fi
Line 377: Line 376:
  echo "creating home mythicalLibrarian and log file">>mythicalLibrarian/output.log
  echo "creating home mythicalLibrarian and log file">>mythicalLibrarian/output.log
  fi
  fi
echo "SEARCH FOUND:""$NewShowName" "ID#:" $seriesid >>"$mythicalLibrarian"/output.log
echo "SEARCH FOUND:""$NewShowName" "ID#:" $seriesid >>"$mythicalLibrarian"/output.log
   
   
  #If series ID is obtained, then get show information.
  #If series ID is obtained, then get show information.
  if [ "$seriesid" != "" ]; then
  if [ ! -z "$seriesid" ]; then
   
   
  #####GET SERIES INFORMATION#####
  #####GET SERIES INFORMATION#####
 
  #Get current server time
  #Get current server time
  curl -s -m"$Timeout" "http://www.thetvdb.com/api/Updates.php?type=none">"$mythicalLibrarian/$NewShowName/current.time"
  curl -s -m"$Timeout" "http://www.thetvdb.com/api/Updates.php?type=none">"$mythicalLibrarian/$NewShowName/current.time"
Line 402: Line 400:
   
   
  #Check for valid time, if blank, then assign 0 value
  #Check for valid time, if blank, then assign 0 value
  test "$LastUpdated" = "" && (LastUpdated="0")
  test ! -z "$LastUpdated" && LastUpdated="0"
   
   
  #Apply Database Update interval to last update time
  #Apply Database Update interval to last update time
Line 408: Line 406:
   
   
   
   
  #####GET EPISODE INFORMATION#####
  #if episode information is out of date or not created
#Compare last updated time to current time to determine if it is time to update database
  if [ "$TvDbTime" -gt "$LastUpdated" ]; then
  if [ "$TvDbTime" -gt "$LastUpdated" ]; then
   
   
#####GET EPISODE INFORMATION#####
  #Strip XML tags
  #Strip XML tags
  seriesid=`echo $seriesid|tr -d "<seriesid>"|tr -d "</seriesid>"`
  seriesid=`echo $seriesid|tr -d "<seriesid>"|tr -d "</seriesid>"`
Line 421: Line 419:
  if [ -f "$mythicalLibrarian/$NewShowName/$NewShowName.xml" ]; then  
  if [ -f "$mythicalLibrarian/$NewShowName/$NewShowName.xml" ]; then  
  cat "$mythicalLibrarian/$NewShowName/$NewShowName.xml" | grep "<EpisodeName>"|replace "  <EpisodeName>" ""|replace "</EpisodeName>" ""|sed 's/;.*//'|tr -d [:punct:]>"$mythicalLibrarian"/"$NewShowName"/"$NewShowName".Ename.txt
  cat "$mythicalLibrarian/$NewShowName/$NewShowName.xml" | grep "<EpisodeName>"|replace "  <EpisodeName>" ""|replace "</EpisodeName>" ""|sed 's/;.*//'|tr -d [:punct:]>"$mythicalLibrarian"/"$NewShowName"/"$NewShowName".Ename.txt
  cat "$mythicalLibrarian/$NewShowName/$NewShowName.xml" | grep "<EpisodeName>"|replace "  <EpisodeName>" ""|replace "</EpisodeName>" ""|tr -d [:punct:]>"$mythicalLibrarian"/"$NewShowName"/"$NewShowName".actualEname.txt
  cat "$mythicalLibrarian/$NewShowName/$NewShowName.xml" | grep "<EpisodeName>"|replace "&amp;" "and"|replace "  <EpisodeName>" ""|replace "</EpisodeName>" ""|tr -d [:punct:]>"$mythicalLibrarian"/"$NewShowName"/"$NewShowName".actualEname.txt
  cat "$mythicalLibrarian/$NewShowName/$NewShowName.xml" | grep "<FirstAired>"|replace "  <FirstAired>" ""|replace "</FirstAired>" ""|replace "/" "">"$mythicalLibrarian"/"$NewShowName"/"$NewShowName".FAired.txt
  cat "$mythicalLibrarian/$NewShowName/$NewShowName.xml" | grep "<FirstAired>"|replace "  <FirstAired>" ""|replace "</FirstAired>" ""|replace "/" "">"$mythicalLibrarian"/"$NewShowName"/"$NewShowName".FAired.txt
  cat $mythicalLibrarian/"$NewShowName"/"$NewShowName".xml | grep "<SeasonNumber>"|replace "<SeasonNumber>" ""|replace "</SeasonNumber>" ""|replace " " "">"$mythicalLibrarian"/"$NewShowName"/"$NewShowName".S.txt
  cat $mythicalLibrarian/"$NewShowName"/"$NewShowName".xml | grep "<SeasonNumber>"|replace "<SeasonNumber>" ""|replace "</SeasonNumber>" ""|replace " " "">"$mythicalLibrarian"/"$NewShowName"/"$NewShowName".S.txt
Line 428: Line 426:
   
   
  elif [ ! -f "$mythicalLibrarian/$NewShowName/$NewShowName.xml" ]; then
  elif [ ! -f "$mythicalLibrarian/$NewShowName/$NewShowName.xml" ]; then
  echo "***FAILURE: curl -s -m$Timeout http://www.thetvdb.com/api/$APIkey/series/$seriesid/all/en.xml">>"$mythicalLibrarian"/output.log
  echo "COULD NOT DOWNLOAD:www.thetvdb.com/api/$APIkey/series/$seriesid/all/en.xml">>"$mythicalLibrarian"/output.log
  fi
  fi
   
   
  #check if files were created and generate message
  #check if files were created and generate message
if [ -f $mythicalLibrarian/"$NewShowName"/"$NewShowName".Ename.txt ]; then
if [ -f $mythicalLibrarian/"$NewShowName"/"$NewShowName".Ename.txt ]; then
echo $TvDbTime>"$mythicalLibrarian/$NewShowName/lastupdated.time"
echo $TvDbTime>"$mythicalLibrarian/$NewShowName/lastupdated.time"
echo "LOCAL DATABASE UPDATED:$mythicalLibrarian/$NewShowName">>"$mythicalLibrarian"/output.log
echo "LOCAL DATABASE UPDATED:$mythicalLibrarian/$NewShowName">>"$mythicalLibrarian"/output.log
elif [ ! -f "$mythicalLibrarian/$NewShowName/$NewShowName.Ename.txt" ]; then
elif [ ! -f "$mythicalLibrarian/$NewShowName/$NewShowName.Ename.txt" ]; then
echo "*** PERMISSION ERROR $mythicalLibrarian/$NewShowName/">>"$mythicalLibrarian"/output.log
echo "*** PERMISSION ERROR $mythicalLibrarian/$NewShowName/">>"$mythicalLibrarian"/output.log
fi
fi
  #Send report to the log if database was not updated.
  #Send report to the log if database was not updated.
  elif [ "$TvDbTime" -le "$LastUpdated" ]; then
  elif [ "$TvDbTime" -le "$LastUpdated" ]; then
Line 446: Line 444:
  #####PROCESS SHOW INFORMATION#####
  #####PROCESS SHOW INFORMATION#####
  #grep use fuzzy logic to find the closest show name from the locally created database and return absolute episode number
  #grep use fuzzy logic to find the closest show name from the locally created database and return absolute episode number
echo $epn >>"$mythicalLibrarian"/output.log
  absolouteEpisodeNumber=`agrep -Byn "${epn:0:29}" "$mythicalLibrarian/$NewShowName/$NewShowName.Ename.txt"|sed 's/:.*//'|grep -m1 ^`
  absolouteEpisodeNumber=`agrep -Byn "${epn:0:29}" "$mythicalLibrarian/$NewShowName/$NewShowName.Ename.txt"|sed 's/:.*//'|grep -m1 ^`
  echo FUZZY Exx NUMBER:$absolouteEpisodeNumber  
  echo FUZZY Exx NUMBER:$absolouteEpisodeNumber  
Line 456: Line 453:
  absolouteEpisodeNumber=`grep -n "$OriginalAirDate" "$mythicalLibrarian""/""$NewShowName""/""$NewShowName"".FAired.txt"|grep -m1 ^|sed 's/:.*//'`
  absolouteEpisodeNumber=`grep -n "$OriginalAirDate" "$mythicalLibrarian""/""$NewShowName""/""$NewShowName"".FAired.txt"|grep -m1 ^|sed 's/:.*//'`
  #Subtract 1 to compensate for original series airdate
  #Subtract 1 to compensate for original series airdate
if [ "$absolouteEpisodeNumber" != "" ]; then
  if [ "$absolouteEpisodeNumber" != "" ]; then
let absolouteEpisodeNumber=$absolouteEpisodeNumber-1
  let absolouteEpisodeNumber=$absolouteEpisodeNumber-1
echo DB ABSOLOUTE Exx NR:$absolouteEpisodeNumber BASED ON ORIG AIR DATE:$OriginalAirDate  
  echo DB ABSOLOUTE Exx NR:$absolouteEpisodeNumber BASED ON ORIG AIR DATE:$OriginalAirDate  
fi
  fi
  fi
  fi
   
   
  #Remove no match found
  #Remove no match found
  if [ "$absolouteEpisodeNumber" = "-1" ]; then
  test "$absolouteEpisodeNumber" = "-1" && absolouteEpisodeNumber=$null
absolouteEpisodeNumber=$null
fi
fi
  fi
  echo "DEFINED ABSOLOUTE EPISODE NUMBER: $absolouteEpisodeNumber">>"$mythicalLibrarian"/output.log
  echo "DEFINED ABSOLOUTE EPISODE NUMBER: $absolouteEpisodeNumber">>"$mythicalLibrarian"/output.log
 
  #if line match is obtained, then gather new episode name, Sxx and Exx
  #if line match is obtained, then gather new episode name, Sxx and Exx
  if [ "$absolouteEpisodeNumber" !=  ""  ]; then
  if [ "$absolouteEpisodeNumber" !=  ""  ]; then
Line 482: Line 476:
  test $sxx -lt 10  && sxx="S0$sxx" || sxx="S$sxx"
  test $sxx -lt 10  && sxx="S0$sxx" || sxx="S$sxx"
  fi
  fi
  echo "EPISODE:$epn ABSOLUTE NUMBER:$absolouteEpisodeNumber" $sxx$exx
echo "EPISODE:$epn ABSOLUTE NUMBER:$absolouteEpisodeNumber" $sxx$exx
   
   
  #if series id is not obtained
  #if series id is not obtained send failure message
  elif [ "$seriesid" == "" ]; then  
  elif [ -z "$seriesid" ]; then  
  echo "series was not found the tvdb or this is a movie may be down try renaming $1">>"$mythicalLibrarian"/output.log
  echo "series was not found the tvdb or this is a movie may be down try renaming $1">>"$mythicalLibrarian"/output.log
   if [ "$Database" = "Enabled" ]; then
   if [ "$Database" = "Enabled" ]; then
  echo "DB ENTIRES- RECSTART:$ShowStartTime- MOVIE:$MovieAirDate- ORIGAIRDATE:$OriginalAirDate- CHID:$ChanID- CAT:$ShowCategory-">>"$mythicalLibrarian"/output.log
  echo "DB ENTIRES- RECSTART:$ShowStartTime- MOVIE:$MovieAirDate- ORIGAIRDATE:$OriginalAirDate- CHID:$ChanID- CAT:$ShowCategory-">>"$mythicalLibrarian"/output.log
  exx=""
  exx=$null
  fi
  fi
  fi
  fi
Line 501: Line 495:
  sudo -u "$NotifyUserName" /usr/local/bin/librarian-notify-send "mythicalLibrarian Error" "Invalid File supplied" error
  sudo -u "$NotifyUserName" /usr/local/bin/librarian-notify-send "mythicalLibrarian Error" "Invalid File supplied" error
  fi
  fi
echo "****** INPUT FILE NAME NON EXISTANT CHECK FILE NAME">>"$mythicalLibrarian"/output.log
  echo "****** INPUT FILE NAME NON EXISTANT CHECK FILE NAME"
  echo "****** INPUT FILE NAME NON EXISTANT CHECK FILE NAME"
echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%">>"$mythicalLibrarian"/output.log
echo "%%%%%%%%%%%%%%%INPUT FILE NAME NON EXISTANT CHECK FILE NAME%%%%%%%%%%%%%%">>"$mythicalLibrarian"/output.log
echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%">>"$mythicalLibrarian"/output.log
  echo $mythicalLibrarian'/mythicalLibrarian.sh "'$1'" "'$2'" "'$3'"'>>$mythicalLibrarian/doover.sh
  echo $mythicalLibrarian'/mythicalLibrarian.sh "'$1'" "'$2'" "'$3'"'>>$mythicalLibrarian/doover.sh
   exit 1  
   exit 1  
Line 531: Line 527:
  AlternateMovieDirWritable=$TMoveDirWritable
  AlternateMovieDirWritable=$TMoveDirWritable
    
    
   
  #report to terminal
  echo "FILE SIZE:$MoveFileSize""kB"
  echo "FILE SIZE:$MoveFileSize""kB"
  echo "MOVEDIR FREE SPACE: $MoveDirFreeSpace"kB"- WRITABLE:$MoveDirWritable"
  echo "MOVEDIR FREE SPACE: $MoveDirFreeSpace"kB"- WRITABLE:$MoveDirWritable"
Line 538: Line 534:
  echo "ALTMOVIEDIR FREE SPACE: $AlternateMovieDirFreeSpace"kB"- WRITABLE:$AlternateMovieDirWritable"
  echo "ALTMOVIEDIR FREE SPACE: $AlternateMovieDirFreeSpace"kB"- WRITABLE:$AlternateMovieDirWritable"
   
   
  #####OUTPUT#####
  #####DEBUG MODE OUTPUT#####
  if [ $DEBUGMODE = "Enabled" ]; then
  if [ $DEBUGMODE = "Enabled" ]; then
  echo "###################DEBUG MODE ENABLED####################">>"$mythicalLibrarian"/output.log
  echo "###################DEBUG MODE ENABLED####################">>"$mythicalLibrarian"/output.log
Line 565: Line 561:
   fi
   fi
   
   
  #Determine where file will fit
  #####FILE HANDLING AND OUTPUT#####
  FailSafeState=0
  FailSafeState=0
  if [ "$MoveDirWritable" != "1" ]; then
  test "$MoveDirWritable" != "1" && MoveDir=$AlternateMoveDir
if [ "$AlternateMoveDirWritable" != "1" ]; then
test "$MoveDirWritable" != "1" -a "$AlternateMoveDirWritable" != "1" && FailSafeState=1
FailSafeState=1
else
MoveDir=$AlternateMoveDir
fi
fi
   
   
  if [ "$PrimaryMovieDirWritable" != "1" ]; then
  #Movie handling: Determine where file will fit
if [ "$AlternateMovieDirWritable" != "1" ]; then
test "$mythicalLibrarianProgramIDCheck" = "MV" -a "$PrimaryMovieDirWritable" != "1" && PrimaryMovieDir=$AlternateMoveDir
FailSafeState=1
test "$mythicalLibrarianProgramIDCheck" = "MV" -a "$PrimaryMovieDirWritable" != "1" -a "$AlternateMovieDirWritable" != "1" && FailSafeState=1
else
PrimaryMovieDir=$AlternateMoveDir
fi
fi
   
   
  #format names for file system
  #format names for file system
Line 587: Line 575:
  NewShowName=`echo $NewShowName|tr -d [:punct:]`
  NewShowName=`echo $NewShowName|tr -d [:punct:]`
  #output Series format  showname=show name sxx=season number exx=episode number epn=episode name
  #output Series format  showname=show name sxx=season number exx=episode number epn=episode name
  if [ "$exx" != "" ]; then
  if [ ! -z "$exx" ]; then
  ShowFileName=`echo "$NewShowName.$sxx$exx ($epn)"`
  ShowFileName=`echo "$NewShowName.$sxx$exx ($epn)"`
  #output Movie Format
  #output Movie Format
  elif [ "$MovieAirDate" != "" ]; then
  elif [ ! -z "$MovieAirDate" -o "$mythicalLibrarianProgramIDCheck" = "MV" ]; then
   ShowFileName=`echo "$NewShowName ($MovieAirDate)"`  
   ShowFileName=`echo "$NewShowName ($MovieAirDate)"`  
  MoveDir="$PrimaryMovieDir"
  MoveDir="$PrimaryMovieDir"
Line 604: Line 592:
  echo "ATTEMPTING SYMLINK TO FAILSAFE DIR: $FailSafeDir">>"$mythicalLibrarian"/output.log
  echo "ATTEMPTING SYMLINK TO FAILSAFE DIR: $FailSafeDir">>"$mythicalLibrarian"/output.log
  echo "ATTEPMTING SYMLINK TO FAILSAFE DIR"
  echo "ATTEPMTING SYMLINK TO FAILSAFE DIR"
ln -s "$3" "$FailSafeDir/$ShowFileName.$originalext"
ln -s "$3" "$FailSafeDir/$ShowFileName.$originalext"
  test -f "$FailSafeDir/$ShowFileName.$originalext";"FAILSAFE MODE COMPLETE: SYMLINK CREATED">>"$mythicalLibrarian"/output.log
  test -f "$FailSafeDir/$ShowFileName.$originalext";"FAILSAFE MODE COMPLETE: SYMLINK CREATED">>"$mythicalLibrarian"/output.log
  test ! -f "$FailSafeDir/$ShowFileName.$originalext";"FAILSAFE MODE FAILURE CHECK PERMISSIONS AND FREE SPACE IN $FailSafeDir">>"$mythicalLibrarian"/output.log
  test ! -f "$FailSafeDir/$ShowFileName.$originalext";"FAILSAFE MODE FAILURE CHECK PERMISSIONS AND FREE SPACE IN $FailSafeDir">>"$mythicalLibrarian"/output.log
  fi
  fi
   
   
  if [ $Notify = Enabled ]; then
  test $Notify = Enabled && sudo -u "$NotifyUserName" /usr/local/bin/librarian-notify-send "mythicalLibrarian FAILSAFE" "FAILSAFE mode active See "$mythicalLibrarian"/output.log for more information" error
sudo -u "$NotifyUserName" /usr/local/bin/librarian-notify-send "mythicalLibrarian FAILSAFE" "FAILSAFE mode active See "$mythicalLibrarian"/output.log for more information" error
  echo $mythicalLibrarian'/mythicalLibrarian.sh "'$1'" "'$2'" "'$3'"'>>$mythicalLibrarian/doover.sh
  fi
echo $mythicalLibrarian'/mythicalLibrarian.sh "'$1'" "'$2'" "'$3'"'>>$mythicalLibrarian/doover.sh
  exit 1  
  exit 1  
  fi
  fi
Line 618: Line 604:
   
   
  if [ "$exx" = "" ]; then
  if [ "$exx" = "" ]; then
  if [ $Notify = Enabled ]; then
  test "$Notify" = "Enabled" && sudo -u "$NotifyUserName" /usr/local/bin/librarian-notify-send "mythicalLibrarian Error" "Could not obtain information from server" error
sudo -u "$NotifyUserName" /usr/local/bin/librarian-notify-send "mythicalLibrarian Error" "Could not obtain information from server" error
  echo "%%%%%%%%%%www.TheTvDB.com information is incomplete $1, $2">>"$mythicalLibrarian"/output.log
  fi
  echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%">>"$mythicalLibrarian"/output.log
  echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%">>"$mythicalLibrarian"/output.log
echo "%%%%%%%%%%www.TheTvDB.com information is incomplete $1, $2">>"$mythicalLibrarian"/output.log
   echo "%%%%%%%%%%%%Please consider helping out and adding to thetvdb%%%%%%%%%%%%">>"$mythicalLibrarian"/output.log
   echo "%%%%%%%%%%%%Please consider helping out and adding to thetvdb%%%%%%%%%%%%"
  echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%">>"$mythicalLibrarian"/output.log
  echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%">>"$mythicalLibrarian"/output.log
  echo $mythicalLibrarian'/mythicalLibrarian.sh "'$1'" "'$2'" "'$3'"'>>$mythicalLibrarian/doover.sh
  echo $mythicalLibrarian'/mythicalLibrarian.sh "'$1'" "'$2'" "'$3'"'>>$mythicalLibrarian/doover.sh
Line 629: Line 613:
  exit 1
  exit 1
  fi
  fi
  #check to see if output folder exists
  #check to see if output folder exists
  if [ -d $MoveDir ]; then
  test -d $MoveDir && echo "VERIFIED DIR: $MoveDir"
echo "VERIFIED DIR: $MoveDir"
   
   
  #If specified, make $movedir = $movedir/show name
  #If specified, make $movedir = $movedir/show name
if [ "$UseShowNameAsDir" = "Enabled" ]; then
test "$UseShowNameAsDir" = "Enabled" && MoveDir=`echo "$MoveDir"/"$NewShowName"`
MoveDir=`echo "$MoveDir"/"$NewShowName"`
   
   
  #Make the folder if it does not exist
  #Make the folder if it does not exist
if [ -d "$MoveDir" ]; then
if [ ! -d "$MoveDir" ]; then
echo "VERIFIED FOLDER: $MoveDir">>"$mythicalLibrarian"/output.log
echo "CREATING FOLDER: $MoveDir">>"$mythicalLibrarian"/output.log
elif [ ! -d "$MoveDir" ]; then
mkdir "$MoveDir"
echo "CREATING FOLDER: $MoveDir">>"$mythicalLibrarian"/output.log
mkdir "$MoveDir"
  #Error message if folder was not created
  #Error message if folder was not created
if [ ! -d "$MoveDir" ];then
if [ ! -d "$MoveDir" ];then
echo "$MoveDir/$NewShowName">>"$mythicalLibrarian"/output.log
echo "COULD NOT CREATE $MoveDir/$NewShowName">>"$mythicalLibrarian"/output.log
echo "##########################################################">>"$mythicalLibrarian"/output.log
echo "##########################################################">>"$mythicalLibrarian"/output.log
echo "#############FAILSAFE MODE HAS BEEN ACTIVATED#############">>"$mythicalLibrarian"/output.log
echo "#############FAILSAFE MODE HAS BEEN ACTIVATED#############">>"$mythicalLibrarian"/output.log
echo "##########################################################">>"$mythicalLibrarian"/output.log
echo "##########################################################">>"$mythicalLibrarian"/output.log
if [ $Notify = "Enabled" ]; then
if [ $Notify = "Enabled" ]; then
sudo -u "$NotifyUserName" /usr/local/bin/librarian-notify-send "mythicalLibrarian error" "failsafe mode activated."  error
sudo -u "$NotifyUserName" /usr/local/bin/librarian-notify-send "mythicalLibrarian error" "failsafe mode activated."  error
fi
SYMLINK=LINK
MoveDir=$FailSafeDir
fi
  fi
  fi
  fi
SYMLINK=LINK
MoveDir=$FailSafeDir
  fi
  fi
  fi
   
   
  #If file exists then make a new name for it
  #If file exists then make a new name for it
Line 671: Line 653:
  if [ ! -f "$MoveDir/$ShowFileName-$mythicalLibrarianCounter.$originalext" ]; then  
  if [ ! -f "$MoveDir/$ShowFileName-$mythicalLibrarianCounter.$originalext" ]; then  
  NameCheck="1"
  NameCheck="1"
if [ -L "$MoveDir/$ShowFileName-$mythicalLibrarianCounter.$originalext" ]; then
NameCheck="0"
fi
  ShowFileName=`echo "$ShowFileName"-"$mythicalLibrarianCounter"`
  ShowFileName=`echo "$ShowFileName"-"$mythicalLibrarianCounter"`
  echo "FILE NAME EXISTS.  FILE WILL BE KNOWN AS: $ShowFileName"
  echo "FILE NAME EXISTS.  FILE WILL BE KNOWN AS: $ShowFileName"
#Report to doover as a questionable file, will not be run unless user requests it.
echo '#QUESTIONABLE#'$mythicalLibrarian'/mythicalLibrarian.sh "'$1'" "'$2'" "'$3'"'>>$mythicalLibrarian/doover.sh
  fi
  fi
  done
  done
# ELIF [ ! "$MoveDir/$ShowFileName.$originalext" ]; then
    
    
  fi
  fi
Line 689: Line 663:
  if [ $SYMLINK != "LINK" ]; then
  if [ $SYMLINK != "LINK" ]; then
   
   
  #Move the file and rename
  #Send notifications, Move the file and rename
  echo "MOVING FILE: $3 to $MoveDir/$ShowFileName.$originalext">>"$mythicalLibrarian"/output.log
  echo "MOVING FILE: $3 to $MoveDir/$ShowFileName.$originalext">>"$mythicalLibrarian"/output.log
test "$Notify" = "Enabled" && sudo -u "$NotifyUserName" /usr/local/bin/librarian-notify-send "mythicalLibrarian Moving" "Moving and renaming $ShowFileName" drive-harddisk
  mv "$3" "$MoveDir/$ShowFileName.$originalext"
  mv "$3" "$MoveDir/$ShowFileName.$originalext"
  #Check and report if file was moved
  #Check and report if file was moved
  if [ -f "$MoveDir/$ShowFileName.$originalext" ]; then
  if [ -f "$MoveDir/$ShowFileName.$originalext" ]; then
  if [ -s "$MoveDir/$ShowFileName.$originalext" ];then
  if [ -s "$MoveDir/$ShowFileName.$originalext" ];then
if [ "$Notify" = "Enabled" ]; then
sudo -u "$NotifyUserName" /usr/local/bin/librarian-notify-send "mythicalLibrarian Moving" "Moving and renaming $ShowFileName" drive-harddisk
fi
  #Send notification to XBMC, Update Library, Clean Library
  #Send notification to XBMC, Update Library, Clean Library
if [ "$XBMCAutomate" = "Enabled" ]; then
  XBMCAutomate
if [ "$XBMCNotify" = "Enabled" ]; then
curl "http://$XBMCIP/xbmcCmds/xbmcHttp?command=ExecBuiltIn(Notification(mythical%20Librarian%2Cadding%20program%20$tvdbshowname%20to%20library))"
fi
curl "http://$XBMCIP/xbmcCmds/xbmcHttp?command=ExecBuiltIn(UpdateLibrary(video))"
curl "http://$XBMCIP/xbmcCmds/xbmcHttp?command=ExecBuiltIn(CleanLibrary)"
fi
  #Create Commercial skip data with file
  #Create Commercial skip data with file
  if [ "$CommercialMarkup" = "Created" ]; then
  if [ "$CommercialMarkup" = "Created" ]; then
Line 711: Line 680:
  echo "$MoveDir/$ShowFileName.txt">>"$mythicalLibrarian"/comskiplog.tracking
  echo "$MoveDir/$ShowFileName.txt">>"$mythicalLibrarian"/comskiplog.tracking
  fi
  fi
  #Make symlink back to original file
  #Make symlink back to original file
  if [ $SYMLINK = "MOVE" ]; then
  if [ $SYMLINK = "MOVE" ]; then
  echo CREATING SYMLINK IN MOVE MODE
  echo CREATING SYMLINK IN MOVE MODE
  ln -s  "$MoveDir/$ShowFileName.$originalext" "$3"
  ln -s  "$MoveDir/$ShowFileName.$originalext" "$3"
  fi
   
   
fi
  #Send notification of completion and exit
  #Send notification of completion and exit
  if [ $Notify = "Enabled" ]; then
  test $Notify = "Enabled" && sudo -u "$NotifyUserName" /usr/local/bin/librarian-notify-send "mythicalLibrarian Sucess" "$ShowFileName moved to $MoveDir" info
sudo -u "$NotifyUserName" /usr/local/bin/librarian-notify-send "mythicalLibrarian Sucess" "$ShowFileName moved to $MoveDir" info
fi
  #Send notification to daily report log
  #Send notification to daily report log
  dailyreport "$ShowFileName"
  dailyreport "$ShowFileName"
Line 728: Line 697:
  elif [ ! -s "$MoveDir/$ShowFileName.$originalext" ]; then
  elif [ ! -s "$MoveDir/$ShowFileName.$originalext" ]; then
  rm "$MoveDir/$ShowFileName.$originalext"
  rm "$MoveDir/$ShowFileName.$originalext"
  if [ $Notify = "Enabled" ]; then
  test $Notify = "Enabled" && sudo -u "$NotifyUserName" /usr/local/bin/librarian-notify-send "mythicalLibrarian Failure" "$ShowFileName could not be moved to $MoveDir" stop
sudo -u "$NotifyUserName" /usr/local/bin/librarian-notify-send "mythicalLibrarian Failure" "$ShowFileName could not be moved to $MoveDir" stop
fi
  echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%">>"$mythicalLibrarian"/output.log
  echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%">>"$mythicalLibrarian"/output.log
  echo "%%%%%%%%%%%%%%%%%%%WROTE 0 LENGTH FILE%%%%%%%%%%%%%%%%%%%%">>"$mythicalLibrarian"/output.log
  echo "%%%%%%%%%%%%%%%%%%%WROTE 0 LENGTH FILE%%%%%%%%%%%%%%%%%%%%">>"$mythicalLibrarian"/output.log
Line 739: Line 706:
  echo "%%%%%%%%%%%%%%PERMISSION ERROR WHILE MOVING%%%%%%%%%%%%%%%">>"$mythicalLibrarian"/output.log
  echo "%%%%%%%%%%%%%%PERMISSION ERROR WHILE MOVING%%%%%%%%%%%%%%%">>"$mythicalLibrarian"/output.log
  echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%">>"$mythicalLibrarian"/output.log
  echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%">>"$mythicalLibrarian"/output.log
  if [ $Notify = "Enabled" ]; then
  test $Notify = "Enabled" sudo -u "$NotifyUserName" /usr/local/bin/librarian-notify-send "mythicalLibrarian Failure" "$ShowFileName could not be moved to $MoveDir" stop
sudo -u "$NotifyUserName" /usr/local/bin/librarian-notify-send "mythicalLibrarian Failure" "$ShowFileName could not be moved to $MoveDir" stop
fi
  fi
  fi
   
   
 
 
  #If symlink is in LINK mode then create symlink
  #If symlink is in LINK mode then create symlink
elif [ $SYMLINK = "LINK" ]; then
elif [ $SYMLINK = "LINK" ]; then
echo "CREATING LINK IN LINK MODE"
echo "CREATING LINK IN LINK MODE"
ln -s "$3" "$MoveDir/$ShowFileName.$originalext"    
echo "ln -s $3 $MoveDir/$ShowFileName.$originalext"
if [ -f "$MoveDir/$ShowFileName.$originalext" ]; then
ln -s "$3" "$MoveDir/$ShowFileName.$originalext"    
echo "Symlink created $MoveDir/$ShowFileName.$originalext""$mythicalLibrarian"/output.log
echo "@@@@@@@@@@@@@OPERATION COMPLETE" `date` "@@@@@@@@@@@@@@@">>"$mythicalLibrarian"/output.log
#if file was created
if [ $Notify = "Enabled" ]; then
if [ -f "$MoveDir/$ShowFileName.$originalext" ]; then
sudo -u "$NotifyUserName" /usr/local/bin/librarian-notify-send "mythicalLibrarian Sucess" "$ShowFileName linked to $MoveDir" info
echo "Symlink created $MoveDir/$ShowFileName.$originalext""$mythicalLibrarian"/output.log
fi
echo "@@@@@@@@@@@@@OPERATION COMPLETE" `date` "@@@@@@@@@@@@@@@">>"$mythicalLibrarian"/output.log
if [ "$Notify" = "Enabled" ]; then
sudo -u "$NotifyUserName" /usr/local/bin/librarian-notify-send "mythicalLibrarian Sucess" "$ShowFileName linked to $MoveDir" info
fi
   #Send notification to XBMC, Update Library, Clean Library
   #Send notification to XBMC, Update Library, Clean Library
if [ "$XBMCAutomate" = "Enabled" ]; then
XBMCAutomate
if [ "$XBMCNotify" = "Enabled" ]; then
curl "http://$XBMCIP/xbmcCmds/xbmcHttp?command=ExecBuiltIn(Notification(mythical%20Librarian%2Cadding%20program%20$tvdbshowname%20to%20library!))"
fi
curl "http://$XBMCIP/xbmcCmds/xbmcHttp?command=ExecBuiltIn(UpdateLibrary(video))"
curl "http://$XBMCIP/xbmcCmds/xbmcHttp?command=ExecBuiltIn(CleanLibrary)"
fi
   
   
  if [ "$CommercialMarkup" = "Created" ]; then
#Move comskip data
mv "$mythicalLibrarian"/markupframes.txt "$MoveDir/$ShowFileName.txt"
  if [ "$CommercialMarkup" = "Created" ]; then
echo "$MoveDir/$ShowFileName.txt">>"$mythicalLibrarian"/comskiplog.tracking
mv "$mythicalLibrarian"/markupframes.txt "$MoveDir/$ShowFileName.txt"
fi
echo "$MoveDir/$ShowFileName.txt">>"$mythicalLibrarian"/comskiplog.tracking
echo "#"$mythicalLibrarian'/mythicalLibrarian.sh "'$1'" "'$2'" "'$3'"'>>$mythicalLibrarian/doover.sh
fi
dailyreport "$ShowFileName"
echo "#"$mythicalLibrarian'/mythicalLibrarian.sh "'$1'" "'$2'" "'$3'"'>>$mythicalLibrarian/doover.sh
exit 0
dailyreport "$ShowFileName"
exit 0
   
   
  #If link failure, send notification and fail
  #If link failure, send notification and fail
elif [ ! -f "$MoveDir/$ShowFileName.$originalext" ]; then
elif [ ! -f "$MoveDir/$ShowFileName.$originalext" ]; then
if [ $Notify = "Enabled" ]; then
echo "PERMISSION ERROR"
sudo -u "$NotifyUserName" /usr/local/bin/librarian-notify-send "mythicalLibrarian Failure" "$ShowFileName could not be linked to $MoveDir" error
echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%">>"$mythicalLibrarian"/output.log
fi
echo "%%%%%%LINK PERMISSION ERROR OR FILE DOES NOT EXIST%%%%%%%%">>"$mythicalLibrarian"/output.log
echo "PERMISSION ERROR"
echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%">>"$mythicalLibrarian"/output.log
echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%">>"$mythicalLibrarian"/output.log
test $Notify = "Enabled" && sudo -u "$NotifyUserName" /usr/local/bin/librarian-notify-send "mythicalLibrarian error" "Failure while creating link. Check permissions" error
echo "%%%%%%LINK PERMISSION ERROR OR FILE DOES NOT EXIST%%%%%%%%">>"$mythicalLibrarian"/output.log
echo $mythicalLibrarian'/mythicalLibrarian.sh "'$1'" "'$2'" "'$3'"'>>$mythicalLibrarian/doover.sh
echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%">>"$mythicalLibrarian"/output.log
fi
if [ $Notify = "Enabled" ]; then
exit 1
sudo -u "$NotifyUserName" /usr/local/bin/librarian-notify-send "mythicalLibrarian error" "Failure while creating link. Check permissions" error
fi  
fi
  echo $mythicalLibrarian'/mythicalLibrarian.sh "'$1'" "'$2'" "'$3'"'>>$mythicalLibrarian/doover.sh
fi
exit 1
fi  
   
   
  #if no match is found then send error messages
  #if no match is found then send error messages
Line 798: Line 756:
  echo "FOR MORE INFORMATION SEE http://wiki.xbmc.org/index.php?title=mythicalLibrarian">>"$mythicalLibrarian"/output.log
  echo "FOR MORE INFORMATION SEE http://wiki.xbmc.org/index.php?title=mythicalLibrarian">>"$mythicalLibrarian"/output.log
  echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%">>"$mythicalLibrarian"/output.log
  echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%">>"$mythicalLibrarian"/output.log
  
   echo "What the heck are you doing here?  You shouldn't be here...  report this!">>"$mythicalLibrarian"/output.log
  fi
  fi
   
   
   
   
  #send notification if enabled
  #send notification if enabled
  if [ $Notify = "Enabled" ]; then
  test $Notify = "Enabled" && sudo -u "$NotifyUserName" /usr/local/bin/librarian-notify-send "mythicalLibrarian error" "mythicalLibrarian operation failed See "$mythicalLibrarian"/output.log for more information" error
sudo -u "$NotifyUserName" /usr/local/bin/librarian-notify-send "mythicalLibrarian error" "mythicalLibrarian operation failed See "$mythicalLibrarian"/output.log for more information" error
  echo $mythicalLibrarian'/mythicalLibrarian.sh "'$1'" "'$2'" "'$3'"'>>$mythicalLibrarian/doover.sh
  fi
  echo $mythicalLibrarian'/mythicalLibrarian.sh "'$1'" "'$2'" "'$3'"'>>$mythicalLibrarian/doover.sh
  exit 1
  exit 1

Revision as of 03:54, 31 December 2009

  1. !/bin/bash
#mythicalLibrarian by Adam Outler
#email: [email protected]
#Software the way it should be: Free and Open Source
#Please contact me with any bug reports 

#Intention:
# This program was designed to be a user job in MythTV.  It can be called by creating a user job.
# This file should be placed in /home/mythtv/mythicalLibrarian
# The user job can be called as follows:
# /home/mythtv/mythicalLibrarian/mythicalLibrarian.sh  "%TITLE%" "%SUBTITLE%" "%DIR%/%FILE%"
#
#Usage:
#  mythicalLibrarian.sh -v "show name" "episode name" "Target Folder"
#  eg. mythicalLibrarian.sh "South Park" "Here Comes the Neighborhood" "/home/mythrecordings/2308320472023429837.mpg"
#  
#Output-target
# If an error occurs and the file cannot be moved, then no change will occur to the original file. If the Movedir
# is full or not available, such as when running a NAS and the computer is disconnected from the network, the 
# AlternateMoveDir will be used. If both of these dirs fail, the show will be SymLinked in the FailSafeDir.
# You may elect to run the user job at a later time when the issue has been resolved.  Output dir and link type 
# will depend  on user settings. The file name however, is preset to the most acceptable standard:
#   Show Title - SxxExx (Episode Title).ext
#
#Symlinking:
# When Symlinking is enabled, mythicalLibrarian will follow its normal mode of operation.  In MOVE mode, 
# mythicalLibrarian will Xreate a symlink from the new file in the same name and location of the old file.  In 
# LINK mode, mythicalLibrarian will not move the file, LINK mode creates a new symlink to the original file. 
# 
#Output-Files
# mythicalLibrarian will create several files in it's working folder.  This is a list of the files and their functions.
# -comskiplog.tracking-keeps track of created comskip.txt files so they can be deleted in the future if their video file
# is deleted.
# -doover.sh is designed to keep track of failed jobs.  It is designed to be executable.  #Commented commands are 
# those which are determined to be questionable.  This file can be made executable and ran after a problem is corrected
# which caused the problem. Questionable commands are those which will require you to add a episode title and set the
# mythicalLibrarian.sh Database=Disabled setting.  Questionable files do not have sufficient guide data.
# -markupstart.txt and markupstop.txt are files which contain information from the last comskip generation.
# Deletion will cause no adverse effects.
# -output.log keeps track of operations and can be used to determine problems.
# -shn.txt, sid.txt, and working.xml are used each time to determine the name and show id of the last show identified.
# -The DailyReport folder is used to log the files which were moved that day.  It can be used as a "program guide" of sorts
# to keep track of what has been added to your library.
#
#Logging:
# Log file will show information for troubleshooting. You can find the log file in the working folder
# Log file default location: /home/mythtv/mythicalLibrarian/output.log
#
#Database-external:
# This program will make 3 calls to TheTvDb for every episode.  The first one is to obtain the series ID and verify the show
# name is correct.  The seccond is to check if the internally managed database is up-to-date.  The third call will only be
# made if the internal database is not up-to-date.  The third call will download a larger file which contains all information
# about the show which is known on TheTvDb.
#
#Database-internal:
# While mythicalLibrarian maintains and requires it's own external file/folder database in the working directory, there is 
# also support for integration with MythTV's internal database.  MythTV Database is required for movies to be recognized and 
# handled by mythicalLibrarian. Also, in the event that the integrated fuzzy logic cannot make a determination of the 
# correct show name, mythicalLibrarian will pull the original air date from the MythTV database and attempt to make an 
# exact match to theTvDb.com supplied data. In addition, the type of program is extracted from the mythtv database and a 
# determination is made weather or not there is sufficient information available to identify the show based upon guide data
# In order to make mythicalLibrarian work to it's full potential, all settings must be filled out correctly under the 
# database section of the user settings. Currently, the only guide data supported is schedulesdirect through mythtv.
#
#Dependencies: depends on "Curl", "agrep", "libnotify-bin" and Mythtv Backend for database access.
# install curl with "apt-get install curl"  
# install agrep with "apt-get install agrep"
# optional: install libnotify-bin with "apt-get install libnotify-bin" 
#
#Ubuntu Notifications:
# In order for mythicalLibrarian to send notifications to the GNOME desktop, it must have no-password sudo access.  It uses
# this access strictly to send complete, moving and failure status notifications.  Because this program is launched by the
# user mythtv under normal circumstances, mythtv must temporarily become your user name in order to send a notification to
# your desktop. This requires the use of a separate script, and for mythtv to have a sudoers group with no password option.
# Notifications are an optional feature
#
#XBMC Notifications:
# If options are enabled, mythicalLibrarian will send a http request to a XBMC Server.  In order for this to work XBMC you
# must ensure that System-service-allow programs on other..


#Show Name Translation
# The user may elect to create a file in the mythicalLibrarian/ working folder which will then translate any recorded
# show name into the desired show name.  This is useful for adding a year to distinguish between a new series
# and an older series and/or typos in your guide data.  By default it should be called "showtranslations" and
# it will be in your home/username/mythicalLibrarian folder.  showtranslations is not needed by most users and the file 
# should only be created if it is needed. Under most circumstances, the integrated fuzzy logic will be 
# sufficient to translate the guide name to the TvDb name, however showtranslations is available to improve 
# accuracy to 100%. The format of showtranslations is as follows:
#Filename: /$mythicalLibrarian/showtranslations
##############################################################
#My Guide Show Title = www.TheTvDb.com Show Title            #
#Battlestar Gallactica = Battlestar Gallactica (2003)        # 
#Millionaire = Who Wants To Be A Millionaire                 #
#Aqua teen Hungerforce = Aqua Teen Hunger Force              #
##############################################################


#######################USER SETTINGS##########################
###Stand-alone mode values###
#MoveDir is the folder which mythicalLibrarian will move the file.  No trailing / is accepted eg. "~/videos"
MoveDir=/home/mythtv/NAS/Video/shows
#AlternateMoveDir will act as a seccondary MoveDir if the primary MoveDir fails.
AlternateMoveDir=/home/mythtv/Shared
#Disable moving of files.  If UseOriginalDir is Enabled, original dir will override MoveDir.  Useful for multiple recording dirs. Enabled|Disabled
UseOriginalDir=Disabled
#When Enabled, mythicalLibrarian will move the file to a folder of the same name as the show. This is not affected by UseOriginalDir. Enabled|Disabled
UseShowNameAsDir=Enabled
#SYMLINK has 3 modes.  MOVE|LINK|Disabled
#Create symlink in original dir from file after MOVE. Do not move just LINK original in MoveDir(overrides moving), Simlinking Disabled 
SYMLINK=MOVE
#DailyReport provides a log of shows added to your library per day. Enabled|Disabled
DailyReport=Enabled
#Internet access Timeout in seconds: Default Timeout=50 (seconds)
Timeout=50 
#Update database time in secconds, Longer duration means faster processing time and less strain on TheTvDb. Default='84000' (1 day)
UpdateDatabase=84000
#mythicalLibrarian working file dir: Default is mythicalLibrarian=~/mythicalLibrarian
mythicalLibrarian=~/mythicalLibrarian
#FailSafe mode will enable symlinks to be formed in FailSafeDir if the move or symlink operation fails.
FailSafeMode=Enabled
#FailSafeDir is used when the file cannot be moved to the MoveDir. FailSafe will not create folders.
FailSafeDir=/home/adam
#If notifications are enabled, NotifyUserName should be the same as the user logged into the GNOME Session.
NotifyUserName=adam
#the following line contains the API key from www.TheTvDb.Com. Default: 6DF511BB2A64E0E9
APIkey=6DF511BB2A64E0E9
#Enables debug mode.  This is a verbose mode of logging which should be used for troubleshooting.  Enabled|Disabled
DEBUGMODE=Enabled

###Reporting/Communications###
#The following line tells mythicalLibrarian to send a notification to GNOME Desktop upon completion. Enabled|Disabled
Notify=Enabled
#Send a notification to XBMC to Update library upon sucessful move job Enabled|Disabled
XBMCUpdate=Enabled
#Send a notification to XBMC to cleanup the library upon sucessful move job Enabled|Disabled
XBMCClean=Enabled
#Send Notifications to XBMC UI when library is updated Enabled|Disabled
XBMCNotify=Enabled
#Ip Address and port for XBMC Notifications Eg.XBMCIP=192.168.1.110:8080
XBMCIP=192.168.1.110:8080
 
###MythTV Database settings### 
#Database access Enabled|Disabled
Database=Enabled
#MySQL User name: Default="mythtv", MySQL access is required to obtain year for movies.
MySQLuser=mythtv
#MySQL Password: Default="mythtv"
MySQLpass=mythtv
#MySQL Myth Database: Default="mythconverg"
MySQLMythDb=mythconverg
#Primary Movie Dir. mythicalLibrarian will attempt to move to this dir first. No trailing / is accepted eg. "~/videos"
PrimaryMovieDir=/home/mythtv/NAS/Video/Movies
#AlternateMoveDir will act as a Seccondary move dir if the primary moive dir fails
AlternateMovieDir=/home/mythtv/Videos
#CommercialMarkup will generate comskip files for recordings when they are moved. 
#Comskips are deleted when mythtv deletes the recording Enabled|Disabled
CommercialMarkup=Enabled

#########################USER SETTINGS########################## 

################################################################
################Do not modify below this line###################
################################################################
echo "@@@@@@@@@@@NEW SEARCH INITIATED AT `date`@@@@@@@@@@@@@">>"$mythicalLibrarian"/output.log 
echo "SEARCH REQUEST:$1 EPISODE:$2 TARGET: $3"

#####DEFINE ENVIRONMENT AND VARIABLES#####
#make our working dir if it does not exist
if [ ! -d "$mythicalLibrarian" ]; then 
	mkdir $mythicalLibrarian
	echo "creating home/mythicalLibrarian and log file">>"$mythicalLibrarian"/output.log
fi

#Set episode name, dir, extension, and showname from the input parameters.
ShowName=$1
epn=`echo $2|sed 's/;.*//'|tr -d [:punct:]`
originalext=`echo "${3#*.}"`
originaldirname=`dirname "$3"`
FileBaseName=${3##*/}  

#Check for show translations relating to the show in question.
if [ -f $mythicalLibrarian/showtranslations ]; then 
	showtranslation=`grep "$ShowName = " "$mythicalLibrarian/showtranslations"|replace "$ShowName = " ""|replace "$mythicalLibrarian/showtranslations" ""`		 
	if [ "$showtranslation" != "$null" ];then 
		ShowName=$showtranslation
		echo "USER TRANSLATION: $1 = $ShowName">>"$mythicalLibrarian"/output.log
	elif [ "$showtranslation" = "$null" ];then
		showtranslation="Inactive"
	fi
fi

#Check for Use Original Dir Parameter
test "$UseOriginalDir" = "Enabled" && MoveDir="$originaldirname"

#Check and make doover.sh if it does not exist
test ! -f "$mythicalLibrarian/doover.sh" && echo 'rm "'$mythicalLibrarian'"/doover.sh'>$mythicalLibrarian/doover.sh
 
#Function daily report data
dailyreport() {
	if [ $DailyReport = Enabled ]; then
		test ! -d "$mythicalLibrarian/DailyReport" && mkdir "$mythicalLibrarian/DailyReport" 
		reportfilename=`date +%Y-%m-%d`
		reporttime=`date +%T`
    		echo "$reporttime "$1>>"$mythicalLibrarian/DailyReport/$reportfilename"
	fi
}
 

#CheckPermissions by writing a small file then deleting it, checking along the way.
#CheckPermissions takes file size, free space on dir, and the dir, then it performs
#tests.  the result will be $TMoveDirWritable as a 1 or a 0 for writable or not.
checkpermissions () { 
if [ "$1" -lt "$2" ]; then
	echo "Testing write permission on $3">$3/arbitraryfile.ext 
	if [ -f "$3/arbitraryfile.ext" -a -s "$3/arbitraryfile.ext" ]; then
		rm "$3/arbitraryfile.ext"
		test ! -f "$3/arbitraryfile.ext" && TMoveDirWritable=1 || TMoveDirWritable=0
	else
		TMoveDirWritable=0
		echo "CHECK PERMISSIONS ON $MoveDir"
	fi
elif [ "$1" -ge "$2" ]; then
	TMoveDirWritable=0
	echo "NO SPACE AVAILBLE ON $3"
fi
}


#Function XBMC Automate handles all communication with XBMC  
XBMCAutomate () {
#Send notification to XBMC, Update Library, Clean Library
test "$XBMCNotification" = "Enabled" && curl "http://$XBMCIP/xbmcCmds/xbmcHttp?command=ExecBuiltIn(Notification(mythical%20Librarian%2Cadding%20program%20$tvdbshowname%20to%20library!))"
test "$XBMCUpdate" = "Enabled" && curl "http://$XBMCIP/xbmcCmds/xbmcHttp?command=ExecBuiltIn(UpdateLibrary(video))"
test "$XBMCClean" = "Enabled" && curl "http://$XBMCIP/xbmcCmds/xbmcHttp?command=ExecBuiltIn(CleanLibrary)"
}


#####MAINTENANCE#####

#Loop through the list of created comskip files and remove orphans.

if [ -f "$mythicalLibrarian/comskiplog.tracking" ]; then
	mythicalLibrarianCounter=0
	while read line
	do
		let mythicalLibrarianCounter=$mythicalLibrarianCounter+1
		FileToCheck=$line
		FileToCheckOriginalDirName=`dirname "$FileToCheck"`
		FileToCheckBaseName="${FileToCheck##*/}"
		FileToCheckBaseName="${FileToCheckBaseName%.*}"
		if [ ! -z "$FileToCheck" ]; then
			FileToCheckLS=`ls "$FileToCheckOriginalDirName"|grep "$FileToCheckBaseName."|sed -n 2p`
	 		if [ -z "$FileToCheckLS" ]; then
				rm $FileToCheck
				echo "ORPHAN FOUND $FileToCheck">>"$mythicalLibrarian"/output.log
			elif [ ! -z "$FileToCheckLS" ]; then
				echo "$FileToCheck">>"$mythicalLibrarian/comskiplog.tracking2"
			fi
		fi
	done <"$mythicalLibrarian/comskiplog.tracking"
 	rm "$mythicalLibrarian/comskiplog.tracking"
 	mv "$mythicalLibrarian/comskiplog.tracking2" "$mythicalLibrarian/comskiplog.tracking"
 fi



#####GATHER INFORMATION FROM MYTHTV DATABASE#####

#Get information if database is enabled
if [ "$Database" = "Enabled" ]; then 

#get chanid for recordings to identify program table
	ChanID=`mysql -u$MySQLuser -p$MySQLpass -e "use '$MySQLMythDb' ; select chanid from recorded where basename like '$FileBaseName';"|sed -n 2p|replace "chanid" ""|replace " " ""`
 
#get ProgramID from recorded to identify program
	ProgramID=`mysql -u$MySQLuser -p$MySQLpass -e "use '$MySQLMythDb' ; select programid from recorded where basename like '$FileBaseName' ; " |sed -n "2p"|replace "starttime" ""`
	mythicalLibrarianProgramIDCheck=${ProgramID:0:2}

#Extrapolate data from Programid
	echo Check: $mythicalLibrarianProgramIDCheck
	test "$mythicalLibrarianProgramIDCheck" = "SH" && ProgramIDType="Generic Episode With No Data"
	test "$mythicalLibrarianProgramIDCheck" = "MV" && ProgramIDType="Movie"
	test "$mythicalLibrarianProgramIDCheck" = "EP" && ProgramIDType="Series With Episode Data"

#if the ProgramID does not meet criteria, then end the program
	if [ "$ProgramIDType" = "Generic Episode With No Data" ]; then
		echo "GENERIC GUIDE DATA WAS SUPPLIED TYPE: $ProgramIDType $1, $2">>"$mythicalLibrarian"/output.log
		echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%">>"$mythicalLibrarian"/output.log
		echo "%%%%%%%%%%%%%%%%%%%PROGRAM GUIDE DATA IS NOT COMPLETE%%%%%%%%%%%%%%%%%%%%">>"$mythicalLibrarian"/output.log
		echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%">>"$mythicalLibrarian"/output.log
 		test $Notify = "Enabled" &&	sudo -u "$NotifyUserName" /usr/local/bin/librarian-notify-send "mythicalLibrarian Guide error" "Could not obtain enough information for library: $ProgramIDType" error
 		echo $mythicalLibrarian'/mythicalLibrarian.sh "'$1'" "'$2'" "'$3'"'>>$mythicalLibrarian/doover.sh
		exit 1
	fi



#get show start time to identify program ----future development
	ShowStartTime=`mysql -u$MySQLuser -p$MySQLpass -e "use '$MySQLMythDb' ; select starttime from recorded where basename like '$FileBaseName' ; " |sed -n "2p"|replace "starttime" ""`

#get category from recorded to identify program table -----future development
	ShowCategory=`mysql -u$MySQLuser -p$MySQLpass -e "use '$MySQLMythDb' ; select category from recorded where basename like '$FileBaseName' ; " |sed -n "2p"|replace "category" ""`

#get original air date for tv shows
	OriginalAirDate=`mysql -u$MySQLuser -p$MySQLpass -e "use '$MySQLMythDb' ; select originalairdate from recorded where basename like '$FileBaseName' ; "|sed -n "2p"|replace "originalairdate" ""`
	test "$OriginalAirDate" = "0000-00-00" && OriginalAirDate="$null"

#get year for movies 
	MovieAirDate=`mysql -u$MySQLuser -p$MySQLpass -e "use '$MySQLMythDb' ; select airdate from recordedprogram where programid like '$ProgramID' and chanid like '$ChanID' ; "|replace "airdate" ""|sed -n "2p"|replace " " ""`

#Blank year if it is invalid
	test ! -z "$MovieAirDate" -a "$MovieAirDate" -lt "1900" && MovieAirDate=$null

#Report found data
	echo RECSTART:$ShowStartTime MOVIEYEAR:$MovieAirDate SERIESDATE:$OriginalAirDate 
	echo PROGRAMID:$ProgramID ShowCategory:$ShowCategory 

#####COMSKIP DATA#####
#Remove old and generate a comskip Start list
	echo $null >$mythicalLibrarian/markupstart.txt
	mysql -u$MySQLuser -p$MySQLpass -e "use '$MySQLMythDb' ; select mark from recordedmarkup where starttime like '$ShowStartTime' and chanid like '$ChanID' and type like "4" ; " |replace "mark" ""|replace " " "">>$mythicalLibrarian/markupstart.txt

#Remove old and generate comskip Stop list
	echo $null >$mythicalLibrarian/markupstop.txt
	mysql -u$MySQLuser -p$MySQLpass -e "use '$MySQLMythDb' ; select mark from recordedmarkup where starttime like '$ShowStartTime' and chanid like '$ChanID' and type like "5" ; " |replace "mark" ""|replace " " "">>$mythicalLibrarian/markupstop.txt

#Set up counter, remove old markup data and generate new markup file from markupstart and stop
	if [ "$CommercialMarkup" = "Enabled" ]; then	
		mythicalLibrarianCounter=1
		echo "FILE PROCESSING COMPLETE">"$mythicalLibrarian"/markupframes.txt
		echo "------------------------">>"$mythicalLibrarian"/markupframes.txt	
		while read line
			do
			mythicalLibrarianCounter=`expr $mythicalLibrarianCounter + 1`;
			StartData=`sed -n "$mythicalLibrarianCounter"p "$mythicalLibrarian/markupstart.txt"`
			StopData=`sed -n "$mythicalLibrarianCounter"p "$mythicalLibrarian/markupstop.txt"`
			if [ ! -z "$StopData" ]; then
				echo "$StartData $StopData">>"$mythicalLibrarian"/markupframes.txt
				CommercialMarkup="Created"
				echo "COMMERCIAL DATA START:$StartData STOP:$StopData"
			fi
		done <"$mythicalLibrarian/markupstop.txt"
	fi
fi 



#####SEARCH FOR SHOW NAME#####
if [ ! -z "$2" -o "$mythicalLibrarianProgramIDCheck" = "EP" ]; then
	 echo "SEARCHING: www.TheTvDb.com SHOW NAME: $ShowName EPISODE: $epn">>"$mythicalLibrarian"/output.log
	 echo "FILE NAME: $3">>"$mythicalLibrarian"/output.log

#Format Show name for Sending to www.TheTvDb.com
	 tvdbshowname=`echo $ShowName|replace " " "%20"`

#download series info for show, parse into temporary text db- sid.txt shn.txt
	 curl -s -m"$Timeout" www.thetvdb.com/api/GetSeries.php?seriesname=$tvdbshowname>$mythicalLibrarian/working.xml
	 cat $mythicalLibrarian/working.xml | grep "<seriesid>"|replace "<seriesid>" ""|replace "</seriesid>" "">$mythicalLibrarian/sid.txt
	 cat $mythicalLibrarian/working.xml | grep "<SeriesName>"|replace "<SeriesName>" ""|replace "</SeriesName>" "">$mythicalLibrarian/shn.txt

#Use fuzzy logic to make the best match of the show name
	 serieslinenumber=`agrep -Byn "${showname:0:27}" $mythicalLibrarian/shn.txt|sed 's/:.*//'|grep -m1 ^`

#Get the seriesid based on the showname
	 seriesid=`sed -n $serieslinenumber'p' $mythicalLibrarian/sid.txt|grep -m1 ^`
	 NewShowName=`sed -n $serieslinenumber'p' $mythicalLibrarian/shn.txt|grep -m1 ^`
elif [ -z "$MovieAirDate" ]; then
	NewShowName=$1
fi

#Create folder for database if it does not exist
if [ ! -d "$mythicalLibrarian/$NewShowName" ]; then
	mkdir $mythicalLibrarian/"$NewShowName"
	echo "creating home mythicalLibrarian and log file">>mythicalLibrarian/output.log
fi
echo "SEARCH FOUND:""$NewShowName" "ID#:" $seriesid >>"$mythicalLibrarian"/output.log

#If series ID is obtained, then get show information.
if [ ! -z "$seriesid" ]; then

#####GET SERIES INFORMATION#####
#Get current server time
	curl -s -m"$Timeout" "http://www.thetvdb.com/api/Updates.php?type=none">"$mythicalLibrarian/$NewShowName/current.time"

#Parse file into usable data only
	cat "$mythicalLibrarian/$NewShowName/current.time"|grep "