#!/bin/bash
## THIS SCRIPT WILL RUN PLEX SCANNER ONLY ON FOLDERS PREVIOUSLY GENERATED BY plexgeneratefolderlist.sh

if pidof -o %PPID -x "$0"; then
   echo "$(date "+%d.%m.%Y %T") Exit, already running."
   exit 1
fi
TIMESTAMP=`date +%Y-%m-%d_%H-%M-%S`
LOGFILE="/home/plex/logs/plexrefresh.cron.log"
UNIONFSPATH="/mnt/unionfs"
RCLONEREMOTE="acdcrypt:"
PLEXLIST="${UNIONFSPATH}/tmp/ "
CACHE="/home/plex/.cache/"
TVSECTION=1
MOVIESECTION=2

export LD_LIBRARY_PATH=/usr/lib/plexmediaserver
export PLEX_MEDIA_SERVER_APPLICATION_SUPPORT_DIR=/var/lib/plexmediaserver/Library/Application\ Support

# EXIT IF THERE ARE NO PLEX LIST FILES
if [[ -z $(find $PLEXLISTPATH -type f -iname "*.list" -mmin +1) ]];then
    echo "Exit: No list available"
    exit
fi
# FIND LISTS, MERGE INTO ONE FILE AND DELETE RLONE REMOTE
find $PLEXLISTPATH -type f -iname "*.list" -mmin +1 |
while read FILEPATH; do
    cat $FILEPATH >> ${CACHE}$TIMESTAMP-plex.list
    FILE=$(basename "${FILEPATH}")
    /usr/bin/rclone delete ${RCLONEPATH2LIST}{$FILE}
done

# REMOVE DUPLICATE FOLDERS
sort $CACHE/$TIMESTAMP-plex.list | uniq | tee $CACHE/$TIMESTAMP-plex.list > /dev/null

# PLEX SCAN NEW FOLDERS
readarray -t FOLDERS < ${CACHE}$TIMESTAMP-plex.list
for FOLDER in "${FOLDERS[@]}"
do
    if [[  $FOLDER == *"/movies/"* ]] ; then
        echo "$(date "+%d.%m.%Y %T") Refreshing movie folder: $FOLDER" | tee -a "$LOGFILE"
        ${LD_LIBRARY_PATH}/Plex\ Media\ Scanner --scan --refresh --section $MOVIESECTION --directory "${FOLDER}" | tee -a "$LOGFILE"
    fi
    if [[  $FOLDER == *"/series/"* ]] ; then
        echo "$(date "+%d.%m.%Y %T") Refreshing serie folder: $FOLDER" | tee -a "$LOGFILE"
        ${LD_LIBRARY_PATH}/Plex\ Media\ Scanner --scan --refresh --section $TVSECTION --directory "${FOLDER}" | tee -a "$LOGFILE"
    fi
done
# ADD SUFFIX DONE TO THE FINISHED LIST
echo "$TIMESTAMP-plex.list.done" | tee -a "$LOGFILE"
mv ${CACHE}$TIMESTAMP-plex.list ${CACHE}$TIMESTAMP-plex.list.done
exit
