Instantly share code, notes, and snippets.

Embed
What would you like to do?
Extract rar-archives in their folder and download subtitles
#!/bin/bash
#
# 2016-07-05 19:46:46
# myrveln@gmail.com
#
# Loop through folder and folders
# Look for rar-files and extract them
# if it's not been extracted before.
#
DIRS=(
"/storage/video/movies"
"/storage/video/tvshows"
)
UNRARBIN="/usr/bin/unrar"
SUBLIMINALBIN="/usr/bin/subliminal"
# Check if we have other processes of this script running
PIDFILE="/tmp/`basename $0`.pid"
if [[ -e ${PIDFILE} ]]; then
PID="`cat ${PIDFILE}`"
if kill -0 &>1 > /dev/null ${PID}; then
# Silent exit as we're already running this script
exit 1
else
rm -f ${PIDFILE}
fi
fi
echo $$ > ${PIDFILE}
#
# Unrar archive
function UnrarThis {
RARFILE="$1"
NEWNAME="$2"
FILE="$3"
EXT="$4"
BASENAME="$(basename ${RARFILE})"
cd "$(dirname ${RARFILE})"
${UNRARBIN} e -ierr -y "${BASENAME}"
mv ${FILE} ${NEWNAME}.${EXT}
echo "Extracted ${NEWNAME}.${EXT}"
}
#
# Pass root-folder to function
function LoopThrough {
for RARFILE in $(/usr/bin/find "${1}" -path '*.rar' -print)
do
DIR="$(dirname "${RARFILE}")"
FILE=`${UNRARBIN} lb ${RARFILE}`
EXT="${FILE##*.}"
NEWNAME="$(echo ${DIR} | rev | cut -d/ -f1 | rev)"
if [[ ! ${NEWNAME} == "Subs" ]]; then
# Check if archived file already exists
if [[ ! -n "$(/usr/bin/find ${DIR}/ -name ${NEWNAME}.${EXT})" ]]; then
# Extract the file
UnrarThis "${RARFILE}" "${NEWNAME}" "${FILE}" "${EXT}"
# Try to download subtitle
${SUBLIMINALBIN} download -l en -f "${DIR}/${NEWNAME}.${EXT}"
else
# Check for subtitles only
# Check if English subtitle exist
if [[ ! -n "$(/usr/bin/find ${DIR}/ -name ${NEWNAME}.en.srt)" ]]; then
${SUBLIMINALBIN} download -l en -f "${DIR}/${NEWNAME}.${EXT}"
fi
fi
fi
done
}
for ROOTFOLDER in "${DIRS[@]}"
do
SAVEIFS=${IFS}
IFS=$(echo -en "\n\b")
LoopThrough "${ROOTFOLDER}"
IFS=${SAVEIFS}
done
# Remove the pid file once the script is done...
if [[ -e ${PIDFILE} ]]; then
rm -f ${PIDFILE}
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment